我想從 API 取回資料,但是當我想將資料放入物件(模型)并將其記錄在控制臺中時,它回傳未定義。
當我在帶有資料系結的 HTML 中使用它時,同樣的事情,它也未定義。但是當我在subscribe函式完成時將它登錄到控制臺時,它確實登錄了控制臺
我的 ts 檔案:
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { BannerStat } from 'src/app/models/banner.model';
import { Home, Banner } from 'src/app/models/home.model';
import { HomeService } from 'src/app/services/home.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class HomeComponent implements OnInit {
home: Home;
bannerList : Banner[];
constructor(private homeService: HomeService) {}
ngOnInit(): void {
this.handleData();
// this gives back undefined banner
// when I use it as data in my html its also undefined
console.log(this.bannerList);
console.log(this.topMessage);
}
handleData(): void {
this.homeService.getHomeObject<Home[]>().subscribe({
next: (response) => {
this.home = response[0];
},
error: (err: any) => {
console.log(err);
},
complete: () => {
this.bannerList = this.home.bannersBanners;
// these both log the correct data
console.log(this.home.topMessage);
console.log(this.bannerList)
}
}
);
}
}
物件和“串列”未在 ngOnInit 或頁面加載時初始化。我也嘗試將“ handleData()”函式放在建構式中,但沒有運氣。
我檢查了多個帖子并瀏覽了網路,但我沒有看到需要更改的地方...
uj5u.com熱心網友回復:
這是由于handleData() 中的異步行程造成的。
問題是 ngOnInit 呼叫 handleData 但不等待答案并繼續通過控制臺記錄物件和串列(js 是這樣作業的,這是正常的)。然后答案來自 api ......但是對于 ngOnInit 中的 console.log 為時已晚。
您可以使用 .toPromise() 解決此問題并在 ngOnInit() 中等待,例如:
await handleData().toPromise().then(response => {console.log(response);}).
uj5u.com熱心網友回復:
您需要像這樣定義 home 變數,home: Home = new Home();然后分配來自 API 的資料。也一樣bannerList:: Banner[] = new Banner[]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/326549.html
下一篇:帶有情感的MUIv5主題/mui
