Angular 9 - 订阅中的变量更改后视图不会更新
Angular 9 - View will not update after variable change in subscribe
在 Anglar 9 中使用订阅 http 客户端时,我无法在 HTML 部分中实现持久行为。我尝试关注 Whosebug 帖子 -
以下是我正在尝试的代码
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();
});
}
我认为你应该使用 async 管道让你的生活更轻松。
ngOnInit(): void {
let urURl = 'https://reqres.in/api/products';
this. list$ = this.http
.get(urURl)
}
app.component.html
{{list$|async|json}}
我已经在 stackblitz
上为您创建了一个演示
在 Anglar 9 中使用订阅 http 客户端时,我无法在 HTML 部分中实现持久行为。我尝试关注 Whosebug 帖子 -
以下是我正在尝试的代码
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();
});
}
我认为你应该使用 async 管道让你的生活更轻松。
ngOnInit(): void {
let urURl = 'https://reqres.in/api/products';
this. list$ = this.http
.get(urURl)
}
app.component.html
{{list$|async|json}}
我已经在 stackblitz
上为您创建了一个演示