在effect中使用RxJS的flatMap操作符等待HttpResponse返回。示例代码如下:
import { Injectable } from '@angular/core';
import { Actions, Effect, ofType } from '@ngrx/effects';
import { Observable, of } from 'rxjs';
import { catchError, map, switchMap } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class UserEffects {
constructor(private actions$: Actions, private http: HttpClient) { }
@Effect()
getUser$: Observable = this.actions$.pipe(
ofType('GET_USER'),
map((action: any) => action.payload),
switchMap((id: number) => {
return this.http.get(`api/user/${id}`).pipe(
map((res) => {
return { type: 'USER_LOADED', payload: res };
}),
catchError((error) => {
return of({ type: 'USER_ERROR', payload: error });
})
);
})
);
}
上一篇:AngularNGRXEffect:Retryifconditionismet
下一篇:AngularNgrxstore-store.select('selectorname')应该返回书籍列表,但却返回了一个不可迭代的列表。