我試圖在 http 呼叫后操作一個變數。我想使用諸如.push()or 之類的函式.forEach(),但它不允許我使用,因為最初沒有將資料分配給變數。
我在控制臺中收到錯誤:
Cannot read properties of undefined (reading 'forEach')
我的組件:
import {Component, OnInit} from '@angular/core';
import {TablesService} from "../tables.service";
@Component({...})
export class BigQueryComponent implements OnInit {
fetchedData: any;
DATA: any;
constructor(private tableService: TablesService) {
this.tableService.fetchAPI().subscribe((data) => {
this.fetchedData = data;
})
}
ngOnInit(): void {
this.getQueryData();
}
getQueryData() {
this.fetchedData.forEach( dataset => {
this.DATA.push( dataset );
});
}
}
我的服務:
export class TablesService {
constructor(private http: HttpClient) {}
fetchAPI() {
return this.http.get('https://.../products');
}
}
我怎么能做到這一點,我試圖將 Observale 添加到 http 函式,但我不確定應該如何正確完成。
uj5u.com熱心網友回復:
基于在評論你的要求,你應該從移動邏輯getQueryData的subscribe功能fetchAPI。因此,當回傳 observable 時,fetchData將被分配data并繼續執行以下邏輯。
并this.tableService.fetchAPI().subscribe從constructor.
通常我們ngOnInit()用于初始化作業,如這個問題中所討論的:Constructor 和 ngOnInit 之間的區別。
constructor(private tableService: TablesService) { }
getQueryData() {
this.tableService.fetchAPI().subscribe((data) => {
this.fetchedData = data;
this.fetchedData.forEach( dataset => {
this.DATA.push( dataset );
});
});
}
筆記:
會提示這兩個變數是用array型別定義的。
fetchedData: any[];
DATA: any[];
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/339121.html
