javascript - 如何在 Angular 4 中调用 httpclient 的 get 方法从服务器检索数据?
问题描述
我正在尝试使用ngrx
. 我想获取数据并保存在商店中。我正在使用ngrx/effect
. 我制作了 reduce、action、@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);
}
推荐阅读
- apache-flink - 为什么 flink 1.7 CEP SQL(MATCH_RECOGNIZE) 不能工作
- r - mutate_at 调节不同的变量 dplyr
- jackson - 将 JSON 属性反序列化为给定的类
- python - 使用 pypdf2 抓取单页 pdf 时不返回文本
- django - 如何在我的 django-login 视图中添加红色星号 (*)?
- text - 如何在记事本++中的每个数字后放置一个点?
- java - Game Ai 使用 Enum 作为有限状态机
- cocoa - 从 Storyboard 创建时,NSSplitViewController 不会折叠
- java - StandardPBEStringEncryptor 类使用的默认值是什么?
- php - 如何在 Doctrine 中建立多对一关系?