我正在嘗試以角度創建圖表,并使用服務獲取資料。我想使用從這里獲取的陣列資料。 pieData: 任意 = []; 建構式內的控制臺正確顯示資料。但 ngOnInit 內的控制臺顯示空陣列。
import { Component, OnInit } from '@angular/core';
import { PieChartService } from './pie-chart.service';
@Component({
selector: 'app-pie-chart',
templateUrl: './pie-chart.component.html',
styleUrls: ['./pie-chart.component.css']
})
export class PieChartComponent implements OnInit {
pieData: any = [];
constructor(private PieChart: PieChartService) {
this.PieChart.getMethod().subscribe((res: any) => {
this.pieData = res.pieData;
console.log(this.pieData);
})
}
ngOnInit() { }
//code for create a graph here
}
uj5u.com熱心網友回復:
您可以嘗試將訂閱移動到 ngOnInit 掛鉤中,以便您可以撰寫代碼或呼叫從訂閱內部創建圖表的函式。雖然我不確定為什么需要在建構式中訂閱,但我想說在建構式中進行作業并不是最佳實踐,因為它主要用于初始化類成員。而在初始化組件的所有資料系結屬性之后呼叫 ngOnInit。
還參考了 ngOnInit 和建構式之間的區別
大多數情況下,我們使用 ngOnInit 進行所有初始化/宣告,并避免在建構式中作業。建構式應該只用于初始化類成員,而不應該做實際的“作業”。
所以你應該使用 constructor() 來設定依賴注入,而不是其他。ngOnInit() 是“開始”的更好地方——它是解決組件系結的地方/時間。
您的問題的解決方案是:
pieData$: Subscription; // subscription for data
ngOnInit() {
this.pieData$ = this.PieChart.getMethod().subscribe((res: any) => {
this.pieData = res.pieData;
console.log(this.pieData);
//code for create a graph here
})
}
也不要忘記取消訂閱 Destroy 的訂閱
ngOnDestroy() {
this.pieData$.unsubscribe();
}
uj5u.com熱心網友回復:
替代方案:使用 Promise
餅組件.ts
import { Component, OnInit } from '@angular/core';
import { PieChartService } from './pie-chart.service';
@Component({
selector: 'app-pie-chart',
templateUrl: './pie-chart.component.html',
styleUrls: ['./pie-chart.component.css'],
})
export class PieChartComponent implements OnInit {
pieData: any = [];
constructor(private PieChart: PieChartService) {
console.log('[PieChartComponent]', '[constructor]');
}
async ngOnInit() {
console.log('[PieChartComponent]', '[OnInit]');
// Follwoing promise is `await`-ed, so execution proceeds once that finishes,
// and after which this.pieData will be set and can be accessed for values
// from anywhere else in the component's lifecycle hooks or any other operations
// that it supports. Enclose within a try-catch for error handling
const pieDataResponse = await this.PieChart.getMethod().toPromise();
this.pieData = pieDataResponse?.pieData || [];
console.log('[PieChartComponent]', '[pieData]', '[Received]', this.pieData);
//code for create a graph here
}
}
WYSIWYG=>WHAT YOU SHOW IS WHAT YOU GET
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/436737.html
下一篇:角度設定路由父子節點
