为什么Ngrx 8.2效果会引发类型不匹配错误

时间:2019-08-10 23:03:23

标签: javascript angular rxjs angular7 ngrx-effects

我做了一个小应用程序,该程序从本地json文件获取数据(产品列表),并在屏幕上显示产品名称。 我有一项从json获取数据的服务:

export class ProductsService {
constructor(private http: HttpClient) {
}

getProducts(): Observable<ProductInterface[]> {
return this.http.get<ProductInterface[]>('assets/data/products.json');
}

效果:

@Injectable()
export class ProductsEffect {

loadProducts$ = createEffect(() =>
this.actions$.pipe(
  ofType(loadProducts),
  switchMap(() => this.productService.getProducts()),
  map((products: ProductInterface[]) => loadProductsSuccess({products})),
  catchError(error => of(loadProductsFailed({error})))
));

constructor(private actions$: Actions, private productService: 
ProductsService) {
}

动作:

export enum productActionNames {
loadProducts = 'LOAD_PRODUCTS',
loadProductsSuccess = 'LOAD_PRODUCTS_SUCCESS',
loadProductsFailed = 'LOAD_PRODUCTS_FAILED',
changeProductPrice = 'CHANGE_PRODUCT_PRICE',
addProduct = 'ADD_PRODUCT',
removeProduct = 'REMOVE_PRODUCT'
}

export const loadProducts = createAction(productActionNames.loadProducts);
export const loadProductsSuccess =         
createAction(productActionNames.loadProductsSuccess, props<{ products: 
ProductInterface[] }>());
export const loadProductsFailed =         
createAction(productActionNames.loadProductsFailed, props<{ error: Error 
}>());
export const changeProductPrice =     
createAction(productActionNames.changeProductPrice, props<{ productName: 
string, newPrice: number }>());
export const addProduct = createAction(productActionNames.addProduct, 
props<{ newProduct: ProductInterface }>());
export const removeProduct = 
createAction(productActionNames.removeProduct, props<{ productName: string 
}>());

即使一切正常,我也会收到此错误消息:

Argument type ()=> Observable({products:ProductInterface[]} & TypedAction) | 
({error:Error} & TypedAction)> is not assignable to parameter type ()=> 
(((...args:any[])=> T extends false? Observable:Observable) | T extends 
false ? Observable:Observable)

我该如何解决?

这是我在github中的项目的链接: https://github.com/1Like1Prayer/temp

1 个答案:

答案 0 :(得分:0)

您应该返回这样的新动作

因为效果期望我们返回动作可观察流

loadProducts$ = createEffect(() =>
this.actions$.pipe(
  ofType(loadProducts),
  switchMap(() => this.productService.getProducts()),
  map((products: ProductInterface[]) => new loadProductsSuccess({products})),
  catchError(error => of(loadProductsFailed({error})))
));