简体   繁体   English

对于 Angular ngIf 异步/可观察 state 更改错误,今天没有好的答案

[英]No good answer today for Angular ngIf async/observable state change bug

Googling around it seems just about anyone who's ever dabbled in Angular has had this issue before:谷歌搜索似乎几乎所有曾经涉足 Angular 的人都曾遇到过这个问题:

you make a Dom element with an *ngIf directive:你使用*ngIf指令创建一个 Dom 元素:

<div *ngIf="array.length">
Don't show me until I'm ready please !
</div>

You have an eval on the spot for whether the child dom should exist.您在现场对子 dom 是否应该存在进行了评估。

then, for example, you receive your data as an api response:然后,例如,您将收到您的数据作为 api 响应:

 this.http.post(
      this.url,
      args,
      this.authenticationService.getRequestOptions()
    ).subscribe(data => {
        this.array = data;
        console.log('truthy? : ', this.array.length);
    }
 );

for some reason the Angular change detect fails at this point and the *ngIf Dom node does not eval and become visible.由于某种原因,此时 Angular 更改检测失败, *ngIf Dom 节点未评估并变为可见。

even though your console gave you:即使您的控制台给了您:

truthy? : 1

What is going on here and what is the best approach?这里发生了什么,最好的方法是什么?

The issue is changeDetect is for all intents and purposes OFF during an ngOnInit lifecycle.问题是 changeDetect 在 ngOnInit 生命周期中的所有意图和目的都是关闭的。 (and you should consider it OFF for things that come before as well such as the constructor) (对于之前的东西,比如构造函数,你应该考虑关闭它)

Only at the ngAfterViewInit lifecycle does the changeDetect start back up.只有在 ngAfterViewInit 生命周期,changeDetect 才会开始备份。

By calling my API within ngAfterViewInit I have a correct result.通过在 ngAfterViewInit 中调用我的 API,我得到了正确的结果。

Just to mention another possible solution.仅提及另一种可能的解决方案。

Its also tipical to do:它也很典型:

someObservable$ = this.http.post(
          this.url,
          args,
          this.authenticationService.getRequestOptions()
);

// or if getRequestOptions() somehow returns an observable:

someObservable$ = this.authenticationService.getRequestOptions().pipe(
    mergeMap((options) => {
        return this.http.post(this.url, args, options);
    })
);
<div *ngIf="(someObservable$ | async)?.length">
    Don't show me until I'm ready please !
</div>

Beware that several things might be missing from this example snippet, like avoiding multiple (Post) requests being done .请注意,此示例代码段中可能缺少几件事,例如避免完成多个 (Post) 请求

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

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