我将@ngrx/store
更新到最新版本8.5.2.
我需要从我的 API 获取数据列表。
现在我创造了action
import { createAction, props } from "@ngrx/store";
import { IListAll } from "./../../list.model";
export const loadLists = createAction("[List] Load Lists");
export const loadListsSuccess = createAction(
"[List] Load Lists Success",
props<{ list: IListAll [] }>()
);
export const loadListsFailure = createAction(
"[List] Load ListFailure",
props<{ error: any }>()
);
到此结束reducer
import { Action, createReducer, on } from "@ngrx/store";
import { IListAll } from "../../list.model";
import * as Listfrom "../actions/list.actions";
export const list= "list";
export interface State {
listAll: IListAll [] | null;
}
export const initialState: State = {
listAll: []
};
const listReducer = createReducer(
initialState,
on(SiteActions.loadLists, state => ({ ...state }))
);
export function reducer(state: State | undefined, action: Action) {
return listReducer(state, action);
}
但是当我尝试将所有内容都设置为effect
import { Injectable } from "@angular/core";
import { Actions, createEffect, ofType } from "@ngrx/effects";
import * as listActions from "../actions/list.actions";
import { concatMap, switchMap } from "rxjs/operators";
import { ListService } from "./../../list.service";
import { IListAll } from "./../../list.model";
import { ListFeatureKey } from './../reducers/list.reducer';
@Injectable()
export class ListEffects {
loadLists$ = createEffect(() =>
this.actions$.pipe(
ofType(listActions.loadLists),
concatMap(() =>
this.listService.getLists().pipe(
map((users: SponsorModel[]) => new actions.LoadSponsorsSuccess(users))
)
)
);
constructor(private actions$: Actions, listService: ListService) {}
}
这是我的service
getLists(): Observable<IListAll[]> {
return this.httpClient.get<IListAll[]>(
environment.BASE_URL + this.API_SITE + "all"
);
}
我收到此错误
类型"可观察"不可分配给类型"可观察 |((...args: any[]( => Observable('. 类型"可观察"不可分配给类型"可观察"。 属性"类型"在类型"{}"中缺失,但在类型"操作"中是必需的。ts(2322(
我知道效果应该总是在最后ngrx
返回一个动作,但我不知道在您的情况下该怎么做
另外,注释掉createEffect(() =>
这有效,但这不是可以的解决方案。
在此更新之前,我使用"OLD"@ngrx方法进行动作/减速器和效果,一切正常, 现在我想转换最新版本规则上的所有内容......
问题在map
函数内:
map((users: SponsorModel[]) => new actions.LoadSponsorsSuccess(users))
从版本8开始,NgRx使用ActionCreators而不是类。操作创建者返回函数,而不是类,因此无需更新操作实例。将其更改为:
map((users: SponsorModel[]) => actions.LoadSponsorsSuccess(users))
我写了一篇关于NgRx Action Creators如何工作的博客文章。它提供有关操作创建者的内部构建块的信息。
在方法周围添加from
运算符:
import { from } from 'rxjs';
from(
this.listService.getLists().pipe(
map((users: SponsorModel[]) => new actions.LoadSponsorsSuccess(users)))
)
)