简体   繁体   English

可观察到的角度* ngif和来自异步调用的数据

[英]Angular *ngif with Observable and data from async calls

I'm using a few REST services to gather data and then change the value of an Observable in my component code. 我正在使用一些REST服务来收集数据,然后在组件代码中更改Observable的值。 I'm trying to use an *ngIf to show/hide div tags based on the result. 我正在尝试使用* ngIf根据结果显示/隐藏div标签。 However, it isn't working, the *ngIf is not updating based on the change to the Observable. 但是,它不起作用,* ngIf不会根据Observable的更改进行更新。

Do I have to trigger change detection? 我必须触发变更检测吗? What's the best way to achieve this in Angular 7? 在Angular 7中实现此目标的最佳方法是什么? Here's one example I tried: 这是我尝试过的一个示例:

HTML: HTML:

<div *ngIf="isAnimal$">
     <p>animal</p>
</div>

Component: 零件:

public isAnimal$: Observable<boolean> = of(false);
...
ngOnInit() {
  checkAnimal();
}

private checkAnimal() {
  this._dataService.getData()
      .subscribe((result) => {
         if (result === 'animal') {
           this.isAnimal$ = of(true);
         }
      });
}

I also tried creating a simple service and that didn't work either. 我还尝试创建一个简单的服务,但也没有用。 Like this: Angular *ngIf binding to function 像这样: Angular * ng如果绑定到函数

I suggest the following: 我建议以下内容:

HTML: HTML:

<div *ngIf="isAnimal">
     <p>animal</p>
</div>

Component: 零件:

public isAnimal: boolean = false;

ngOnInit() {
  checkAnimal();
}

private checkAnimal() {
  this._dataService.getData().subscribe(
    (result) => {
       if (result === 'animal') {
         this.isAnimal = true;
       }
    },
    (error) => {
      console.log(error);
    }
 );
}

I am not sure, but I think you could use the async pipe instead using your implementation: 我不确定,但是我认为您可以使用异步管道来代替实现:

<div *ngIf="isAnimal$ | async">
     <p>animal</p>
</div>

The reason your solution is not working is because isAnimal$ is an observable that has to be resolved. 您的解决方案无法正常工作的原因是, isAnimal$是一个必须解决的可观察对象。 The async pipe could do this, but I prefer the first solution to be honest. 异步管道可以做到这一点,但是老实说,我更喜欢第一个解决方案。 It does not seem natural to me to create another observable of(true) in your subscription. 在您的订阅中创建另一个可观察of(true)对我来说似乎并不自然。

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

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