gab*_*ric 11 redux ngrx angular
我有一组静态数据,一组国家,用于某些组件.这些数据加载到ngOnInit()这些组件中,但我想加载它们只是在我第一次请求数据时(存储是空的).每次我加载组件时我只想使用商店中的数据而不"刷新"它.
如何使用ngrx实现这一目标?
我正在使用效果.这是我的代码的样子:
组件:
export class EditPageComponent implements OnInit {
countries$: Observable<Country[]>
constructor(private store: Store<fromContacts.State>) {
this.countries$ = store.select(fromContacts.getCountriesEntities);
}
ngOnInit() {
this.store.dispatch(new countries.Load());
}
Run Code Online (Sandbox Code Playgroud)
效果:
@Effect()
loadCollection$: Observable<Action> = this.actions$
.ofType(countries.LOAD)
.switchMap(() =>
this.countriesService
.getCountries()
.map((countriesList: Country[]) => {
return new countries.LoadSuccess(countriesList);
})
.catch(error => of(new countries.LoadFail(error)))
);
Run Code Online (Sandbox Code Playgroud)
还原剂:
case countries.LOAD_SUCCESS: {
const countriesList: Country[] = action.payload;
const reducedCountries: { [id: string]: Country } = countriesList.reduce((countrs: { [id: string]: Country }, countr: Country) => {
return Object.assign(countrs, {
[countr.code]: countr
});
}, {});
Run Code Online (Sandbox Code Playgroud)
谢谢,加布
tim*_*ver 11
您可以从效果中的商店中选择国家/地区,如果它们在商店中代表我们忽略操作,否则我们获取国家/地区。
@Effect()
getOrder = this.actions.pipe(
ofType<GetOrder>(ActionTypes.GetOrder),
withLatestFrom(this.store.pipe(select(getOrders))),
filter(([{payload}, orders]) => !!orders[payload.orderId])
mergeMap([{payload}] => {
...
})
)
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅为此开始使用 ngrx/effects。
Het*_*ies 10
有不同的方法可以做到这一点.首先,您可以将hasLoaded: boolean房产保留在州.然后,您可以在进行服务调用之前检查此信息.
ngOnInit() {
this.store.select(getHasLoaded)
.take(1)
.subscribe(hasLoaded => {
if (!hasLoaded) this.store.dispatch(new countries.Load());
}
}
Run Code Online (Sandbox Code Playgroud)
另一个选择是让你的@Effect检查hasLoaded属性:
@Effect()
loadCollection$: Observable<Action> = this.actions$
.ofType(countries.LOAD)
.withLatestFrom(this.store.select(getHasLoaded)
.filter(([ action, hasLoaded ]) => !hasLoaded) // only continue if hasLoaded is false
.switchMap(() =>
this.countriesService
.getCountries()
.map((countriesList: Country[]) => {
return new countries.LoadSuccess(countriesList);
})
.catch(error => of(new countries.LoadFail(error)))
);
Run Code Online (Sandbox Code Playgroud)
为此,您需要在Effects构造函数中提供商店.
小智 8
take(1)在效果中使用运算符不要忘记使用
catchErrorand return 进行错误处理EMPTY,否则当发生错误时,该错误将始终返回(超时,身份验证错误,离线...)
我和您的情况完全一样,我所做的只是在效果中添加了rxjs运算符,take以便仅在第一次LoadCountries派发该动作时才获取国家/地区。
@Effect()
loadCountries$: Observable<CoreActions> = this.actions$.pipe(
ofType(CoreActionTypes.LoadCountries),
mergeMap(() =>
this.countriesService.getAllCountries().pipe(
map(c => new LoadCountriesSuccess(c)),
catchError(() => {
this.store.dispatch(new LoadCountriesFailed());
return EMPTY;
})
)
),
take(1)
);
Run Code Online (Sandbox Code Playgroud)
返回EMPTY内部catchError将完成可观察的结果,而不会通过take(1)
| 归档时间: |
|
| 查看次数: |
5382 次 |
| 最近记录: |