我有一个 ng-container,必须显示以防某些可观察值具有值,如果没有,则必须显示 ng-template:
<ng-container *ngIf="obs$ | async; else template">
<router-outlet></router-outlet>
</ng-container>
<ng-template #template>
<div>
No data
</div>
</ng-template>
但是,当我在订阅后记录可观察值的值时,我发现它实际上有一个值,所以我不明白这里的问题是什么。
以下是 obs$ observable 的设置方式:
obs$: Observable<Promise<SomeClass | null>> =
this.obs2$.pipe(
map(async (foo: SomeOtherClass | null) => {
if (!foo) {
return null;
}
const { id } = foo;
const bar = await this.someService.getBarById(
id
);
return bar;
})
);
您需要使用
switchMap
而不是使用 map
来使用 async and await
,它基本上做同样的事情。
obs$ = of(null).pipe(
switchMap(() => {
// replace below line with: return this.someService.getBarById(id);
return of(true).pipe(delay(5000)); // simulates an API call!
})
);
import { Component } from '@angular/core';
import { provideRouter, RouterOutlet } from '@angular/router';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';
import { CommonModule } from '@angular/common';
import { ChildComponent } from './app/child/child.component';
import { map, timeout, delay } from 'rxjs/operators';
import { of, interval, switchMap } from 'rxjs';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet, CommonModule],
template: `
<ng-container *ngIf="obs$ | async; else template">
<router-outlet></router-outlet>
</ng-container>
<ng-template #template>
<div>
No data
</div>
</ng-template>
`,
})
export class App {
name = 'Angular';
obs$ = of(null).pipe(
switchMap(() => {
return of(true).pipe(delay(5000));
})
);
}
bootstrapApplication(App, {
providers: [
provideRouter([
{
path: 'default',
component: ChildComponent,
},
{
path: '**',
redirectTo: 'default',
pathMatch: 'full',
},
]),
],
});