angular - Angular 9 - 订阅中的变量更改后视图不会更新
问题描述
在 Angular 9 中使用订阅 http 客户端时,我无法使其在 HTML 部分中保持持久行为。我尝试关注 stackoverflow 帖子 -
- 订阅中的变量更改后,Angular 2 View 不会更新
- https://html.developreference.com/article/11972625/Angular+6+View+is+not+updated+after+changed+a+variable+within+subscribe
以下是我正在尝试的代码
export class BaseComponent implements OnInit, OnDestroy {
list: any[];
unsubscribe$: Subject<any> = new Subject();
constructor(private ngZone: NgZone,private changeRef: ChangeDetectorRef) {
}
ngOnInit(): void {
return this.http
.get(environment.apiBaseUrl + url, this.getOptions())
.pipe(takeUntil(this.unsubscribe$))
.subscribe(()=>{
this.ngZone.run(()=>{
this.list = response.data;
})
this.list = response.data;
this.changeRef.detectChanges();
this.changeRef.markForCheck();
});
}
ngOnDestroy(): void {
this.unsubscribe$.next();
this.unsubscribe$.complete();
}
}
// Nothing working for me.
解决方案
如果您使用策略,您的onInit
功能应该是这样的:onPush
ngOnInit(): void {
return this.http
.get(environment.apiBaseUrl + url, this.getOptions())
.pipe(takeUntil(this.unsubscribe$))
.pipe(retry(3), catchError(this.handleError));
.subscribe(response => {
this.list = response.data;
this.changeRef.markForCheck();
});
}
推荐阅读
- javascript - 在javascript中重定向网页
- html - 为什么列和换行中的 flexbox 被破坏
- java - 如何使用电报 api 从 chatid 中保存 id
- typeerror - TypeError:无法解压不可迭代的 int 对象以进行数据集扩充
- node.js - 尝试代理 websocket 并且在 setupProxy 中未建立连接
- reactjs - react-native 类组件中的替代 useState
- pytorch - 如何在 PyTorch 中获得组合网络的正确梯度?
- javascript - 一些图标点击监听器在 JavaScript 中可以正常工作,而另一些则不是很奇怪
- python - 不同 ID 的 Ngram,显示在一行中
- php - 如何在 Laravel / Lumen 8 的控制器中获取控制器和动作名称?