首页 > 解决方案 > 如何解决承诺对象

问题描述

我想从服务使用的ngrx/store 中获取数据,然后我从reducer 获得一个promise 对象,如何解析promise 对象以显示在网页上。

服务

get(request){
  return this.httpClient.get<any>(uri).toPromise().then(res => <Node[]>res);
}

行动

getNodeData(name){
    return this.service.get(name);
}

减速器

export function nodeReducre(
  state = initNode,
  action: Action
) {
  switch (action.type):
    case 'GetNode':
      state = action.getNodeData(name);
      return state;
    default:
      return initNode;
}

组件.ts

node$: Observalbe<Node[]> = this.store.pipe(select('node'));

组件.html

{{node$|async}}

在网页上显示“[object Promise]”。

stackblitz 演示:https ://stackblitz.com/edit/angular-yebobf

标签: angularngrx

解决方案


You are trying to working with async actions in ngrx. Async actions are handled using the effects. I have updated forked your working demo and did some changes using effects. I created an effect as app-effect.ts in your sample. Observe some changes done by me in app.component.ts, app.module.ts, app-reducer.ts, app-action.ts

@Injectable()
export class AppEffects {
  constructor(
    private actions$: Actions,
    public nodeSvc: DemoService
  ) {}

  @Effect()
  viewNodes$ = this.actions$
    .pipe(
      ofType(DemoActions.requestNodeAction),
      mergeMap((data) => {
        return this.nodeSvc.getObjectCallChain(data.payload)
        .pipe(
          map(data => ({ type: DemoActions.receivedNodeAction, payload: data })),
          catchError(() => EMPTY)
        )
      })
      )
}

You can find the updated example here

https://stackblitz.com/edit/angular-gni7vu

Also, you can study in details about ngrx effects here

https://ngrx.io/guide/effects


推荐阅读