我正在開發一個有角度的應用程式。在我的組件.ts檔案中,我有一個陣列,如下所示:
public myArray = [];
public dataFromAPI = [];
每當我嘗試推送此陣列中的元素時,在我的一種方法中,它都會給我以下錯誤:
this.appService.getData.subscribe(resp => {
if (resp != null) {
this.dataFromAPI = resp;
this.dataFromAPI.forEach(element => {
this.myArray.push(element)
})
}
RROR TypeError: Cannot read properties of null (reading 'push')
我在我的代碼中沒有看到任何錯誤。我總是像這樣定義一個新陣列,但我第一次收到此錯誤。如何解決這個問題?
uj5u.com熱心網友回復:
宣告應如下所示
public myArray:any = [];
public dataFromAPI:any = [];
你應該像下面這樣直接回圈api的回應(請檢查里面回應物件中可能有更多的鍵,通過鍵訪問陣列)
this.appService.getData.subscribe(resp => {
if (resp != null) {
resp.data.forEach(element => {
this.myArray.push(element)
});
this.dataFromAPI = resp;
}
}
uj5u.com熱心網友回復:
我不確定什么是語法public myArray = [];。下面將適用于打字稿。
const myArray: string[] = [];
myArray.push('string');
const myArray: number[] = [];
myArray.push(123);
const myArray: Record<string, unknown>[] = [];
myArray.push({key: 'value'});
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/403086.html
標籤:
上一篇:與react-hook-form一起使用時,自定義React組件不顯示輸入長度
下一篇:如何檢查我沒有的例外型別?
