在 ngIf 中使用时 Observable 不执行
Observable doesn't execute when used in ngIf
我正在尝试根据在模板中的 if 条件中使用的布尔可观察对象来执行可观察对象 chain/pipe。
但是 pipe() 语句中的代码永远不会执行,即使我在模板中的 boolean observable 上使用异步管道。
<div>{{isAllowed$ | async}} --- resolves to true or false and shows on html page
<div *ngIf="isAllowed$ | async>
//other items
</div>
ngOnInit() {
this.isAllowed$ = callToMethodThatReturnsBooleanObservalble();
this.isAllowed$.pipe(
tap(val => { // -- never gets executed
if(val) {
//make rest call --- never gets executed
}
})
)
}
如果我将 subscribe() 放在管道的末尾,它确实有效,但我认为异步管道为我们做到了。
您需要将管道添加到您进行的调用中:
ngOnInit() {
this.isAllowed$ = callToMethodThatReturnsBooleanObservalble().pipe(
tap(val => {
if(val) {
}
})
);
}
pipe
方法创建了一个新的 Observable
,因此当您像以前那样操作时,不会存储该 observable,也不会在模板中订阅
您可以使用 Rxjs 主题。这也可用作可观察对象,并且可以在您想要更新数据更改时使用 'next' 发出数据。无需手动订阅,因为您使用的是“异步”管道。
您可以在代码中使用类似的东西。
<div>
<div *ngIf="(isAllowed$ | async)">
//other items
</div>
</div>;
// In your .ts file //
public isAllowed$ = new Subject<boolean>();
ngOnInit() {
// Pass your function that returns a boolean in your subject isAllowed.
// and your subscription will trigger whenever there is a change
this.isAllowed$.next(callToMethodThatReturnsBooleanObservalble());
}
我正在尝试根据在模板中的 if 条件中使用的布尔可观察对象来执行可观察对象 chain/pipe。
但是 pipe() 语句中的代码永远不会执行,即使我在模板中的 boolean observable 上使用异步管道。
<div>{{isAllowed$ | async}} --- resolves to true or false and shows on html page
<div *ngIf="isAllowed$ | async>
//other items
</div>
ngOnInit() {
this.isAllowed$ = callToMethodThatReturnsBooleanObservalble();
this.isAllowed$.pipe(
tap(val => { // -- never gets executed
if(val) {
//make rest call --- never gets executed
}
})
)
}
如果我将 subscribe() 放在管道的末尾,它确实有效,但我认为异步管道为我们做到了。
您需要将管道添加到您进行的调用中:
ngOnInit() {
this.isAllowed$ = callToMethodThatReturnsBooleanObservalble().pipe(
tap(val => {
if(val) {
}
})
);
}
pipe
方法创建了一个新的 Observable
,因此当您像以前那样操作时,不会存储该 observable,也不会在模板中订阅
您可以使用 Rxjs 主题。这也可用作可观察对象,并且可以在您想要更新数据更改时使用 'next' 发出数据。无需手动订阅,因为您使用的是“异步”管道。
您可以在代码中使用类似的东西。
<div>
<div *ngIf="(isAllowed$ | async)">
//other items
</div>
</div>;
// In your .ts file //
public isAllowed$ = new Subject<boolean>();
ngOnInit() {
// Pass your function that returns a boolean in your subject isAllowed.
// and your subscription will trigger whenever there is a change
this.isAllowed$.next(callToMethodThatReturnsBooleanObservalble());
}