首页 > 解决方案 > 如何在 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;
}

标签: javascriptangularngrxngrx-store

解决方案


好的,首先你应该创建一个效果文件并包含在你的 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);
  }

推荐阅读