首页 > 解决方案 > Angular 9 - 订阅中的变量更改后视图不会更新

问题描述

在 Angular 9 中使用订阅 http 客户端时,我无法使其在 HTML 部分中保持持久行为。我尝试关注 stackoverflow 帖子 -

  1. 订阅中的变量更改后,Angular 2 View 不会更新
  2. 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.


  

标签: angularangular9subscribe

解决方案


如果您使用策略,您的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();
            });

  }

推荐阅读