繁体   English   中英

Angular 9 - 订阅中的变量更改后视图不会更新

[英]Angular 9 - View will not update after variable change in subscribe

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

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


  

如果您使用onPush策略,您的onInit function 应该是这样的:

 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();
            });

  }

我认为你应该通过使用异步管道让你的生活更轻松。

ngOnInit(): void {
    let urURl = 'https://reqres.in/api/products';
     this. list$ = this.http
            .get(urURl)

  }

app.component.html

{{list$|async|json}}

我在stackblitz上为你创建了一个演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM