gpt4 book ai didi

angular6 - 当我在获取数据后调度操作时无限循环/订阅

转载 作者:行者123 更新时间:2023-12-02 19:51:23 27 4
gpt4 key购买 nike

我是 Angular 6 和 ngrx 商店的新人。我尝试在从商店订阅数据后调度操作,但它会导致无限循环并使浏览器崩溃?我错了什么。我发现它使用 rxjs 的 do/tap 运算符但仍然不起作用的一些解决方案。例如,当我使用 {{(feedState | async).loading}} 时,它总是返回 undefined 。

我的组件:

  ngOnInit() {
this.store.dispatch(new FeedActions.GetFeedCategories());
this.feedSubscription = this.store
.pipe(
select('feed'),
map(data => {
this.feedState = data;
return data.categories;
}),
tap(data =>
this.store.dispatch(
new FeedActions.GetFeedItems({
cat_id: data[this.selectedIndex],
page: 0
})
)
)
)
.subscribe(data => {});
}

最佳答案

选择运算符将创建一个可观察对象,每次更新“feed”状态时都会发出该可观察对象。当您执行 FeedActions.GetFeedCategories() 时,这将第一次触发但当 FeedActions.GetFeedItems(...) 的结果时它也会再次触发添加到状态中,这将导致 FeedActions.GetFeedItmes(...)一次又一次地被执行...

简单的解决方案是将 take(1) 添加到管道中,这样您就只能获得一次 map 和点击操作符的触发:

ngOnInit() {
this.store.dispatch(new FeedActions.GetFeedCategories());
this.feedSubscription = this.store
.pipe(
select('feed'),
take(1),
map(data => {
this.feedState = data;
return data.categories;
}),
tap(data =>
this.store.dispatch(
new FeedActions.GetFeedItems({
cat_id: data[this.selectedIndex],
page: 0
})
)
)
)
.subscribe(data => {});
}

但是,可能值得考虑在这里分开关注 - 您将准备状态的工作与选择要显示的状态的工作混合在一起。更好的解决方案可能是这样的:

ngOnInit() {
this.store.dispatch(new FeedActions.GetFeedCategories());
this.store.pipe(
select('feed'),
take(1),
map(data => data.categories),
tap(data =>
this.store.dispatch(
new FeedActions.GetFeedItems({
cat_id: data[this.selectedIndex],
page: 0
})
)
)
)
.subscribe(() => {});

this.feedState = this.store.pipe(
select('feed')
);
}

...然后在您的模板中,您可以使用 {{feedState | async}}?.loading或任何需要的东西。

async Pipe 为您进行订阅,并需要一个可观察的字段,而不是原始数据字段。在您的示例中, this.feedState 的类型应为 Observable<FeedState> ,但从提供的代码来看它似乎是原始数据类型(例如 FeedState 而不是 Observable)。

关于angular6 - 当我在获取数据后调度操作时无限循环/订阅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52072763/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com