我正在尝试使用ngrx
从服务器获取数据。我想获取数据并保存在商店中。我正在使用ngrx/effect
。我制作reduces,@effect文件。现在我想知道调用此函数,以便我将获取数据并保存在我的应用程序状态中
这是我的代码https://stackblitz.com/edit/angular-kewril?file=src%2Fapp%2Fapp.module.ts
动作
import {Action} from '@ngrx/store';
export const FETCH_BANKLIST = 'FETCH_BANKLIST';
export class FetchRecipe implements Action {
readonly type = FETCH_BANKLIST;
}
export type BankAction = FetchRecipe;
减速器
import * as bankActions from './bank.action';
export interface Bank {
seo_val: string;
text_val: string;
}
export interface State {
isLoading: boolean;
isLoadSuccess: boolean;
banks: Array<Bank>;
}
export const initialState: State = {
isLoading: false,
isLoadSuccess: false,
banks: []
};
export function BankListReducer(state = initialState, action: bankActions.BankAction) {
return state;
}
[好,首先您应该创建一个效果文件,并将其包含在您的EffectsModule中
[app.module.ts
文件,这里是创建效果的代码供您参考。
@Effect()
getData$: Observable<Action|any> = this.actions$
.ofType(actions. FETCH_BANKLIST)
.map((action:actions. FetchRecipe) => action.payload)
.switchMap(payload => this.apiServices.fetchRecipies(payload)
.map(result => {
return new actions.SaveRecipieDetails(result);
})
.catch(e => {
return new actions.ApiError(e);
})
);
因此,每当您调度FETCH_BANKLIST时,您的效果就会被触发,并使用服务进行API调用。
app.services.ts
fetchRecipies(payload) {
const requestUrl = environment.apiUrl;
return this.http.post(requestUrl, payload);
}