當前代碼正在嘗試使用異步管道方法,而不是在訂閱中使用分配。但是,如果服務中發生延遲,則初始值不會在模板中呈現,當資料準備好時,值會按預期呈現,我試圖模仿我使用這個時呈現的呈現行為。標題2。
組件:
title$: Observable<string> = of('Default Title'); // I am not sure if this assignation is right
title2 = 'Default Title 2';
constructor(private sampleService: SampleService) {}
// Load title has a delay in the response
this.title$ = this.sampleService.loadTitle();
this.sampleService.loadTitle().subscribe((title) => {
this.title2 = title; // the assignation
});
模板:
<h4>{{ title$ | async }}</h4>
<h4>{{ title2 }}</h4>
樣本在這個 stackblitz
uj5u.com熱心網友回復:
我想你想用startWith來做一個可觀??察的初始值。嘗試將代碼更改為此,它可以作業。
this.title$ = this.sampleService
.loadTitle()
.pipe(startWith('Default Title'));
uj5u.com熱心網友回復:
有幾種方法可以解決此問題,但鑒于您提供的代碼,您可以switchMap按如下方式使用運算子:
更新this.title$ = this.sampleService.loadTitle();到this.title$.pipe(switchMap(() => this.sampleService.loadTitle()));
您當前正在做的是用不同的值覆寫 title$ 屬性。switchMap使得每次第一個 observable 發出一個值時(在你的情況下,這只發生一次你的of('Default Title'))它會轉身并創建另一個 observable,然后它將觀察發出的值。
uj5u.com熱心網友回復:
您可以使用 ng-container 訂閱您的 observable 并重命名它,以便在資料準備好時,您可以簡單地將其用作模板中的常規變數。 堆疊閃電戰
容器.component.ts
export class ItemsComponent implements OnInit {
@Input() name: string;
items$: Observable<string[]>;
title$: Observable<string>;
constructor(private sampleService: SampleService) {}
ngOnInit() {
this.title$ = this.sampleService.loadTitle();
this.items$ = this.sampleService.loadItems();
}
}
container.component.html
<ng-container *ngIf="title$ | async as title">
<h4>{{ title }}</h4>
</ng-container>
<ng-container *ngIf="items$ | async as items">
<list *ngIf="items.length" [items]="items"></list>
</ng-container>
請記住,無論您在哪里使用異步一詞,它都是一個新訂閱。
如果您在模板中多次在同一個 observable 上使用異步管道,則您正在創建多個訂閱。
如果您希望使用與服務呼叫不同的起始值,則使用 startWith 運算子也是一個不錯的選擇。使用 startWith 的一個好地方是 formControl valueChanges 可觀察的,因為它沒有起始值,并且僅在值更改時觸發。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/477811.html
標籤:javascript 有角度的 rxjs 可观察的 异步管道
