我正在從 API 獲取資料,并且正在初始化資料,如下所示:
export class ForumComponent implements OnInit {
@Input() id_foro: number = 3;
nombre: string = '';
desc: string = ''
foro!: Forum;
constructor(private forumService: ForumService) { }
ngOnInit(): void {
this.forumService.getById(this.id_foro).subscribe((data: Forum) => {
this.foro = data;
});
}
}
我怎么能這樣做?
forum: Forum = this.forumService.getById(this.id_foro).subscribe();
GetById 函式:
getById(id: number): Observable<Forum> {
return this.httpClient.get<Forum[]>(`http://localhost:3000/forum/${id}`)
.pipe(map((response: Forum[]) => response[0]));
}
uj5u.com熱心網友回復:
getById已經回傳了一個 observable,所以不需要訂閱。| async只需使用管道對回應做出反應。
我建議洗掉!除非您 100% 確定,否則總會有一個值(我認為我對此表示懷疑)。
讓我們添加$以表明它是一個可觀察的(它只是一種命名變數的方式,沒有其他花哨的東西)。
foro$: Observable<Forum> = this.forumService.getById(this.id_foro);
<div>{{ foro$ | async }}</div>
編輯以從可觀察物件訪問物件
<div *ngIf="(foro$ | async)?.nombre">{{ (foro$ | async)?.nombre }}</div>
<ng-container *ngIf="foro$ | async as forum">
<div *ngFor="let prop of forum | keyvalue">
Key: <b>{{prop.key}}</b> and Value: <b>{{prop.value}}</b>
</div>
</ng-container>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/472461.html
上一篇:如何檢查網站是基于Angular還是Angularjs構建的?
下一篇:停止以根據條件帶來重復的結果
