我使用一項服務來填充我的 observable 來自后端的資料。后端正在傳遞正確的資料。現在我想獲取 observable 的值并構建一個餅圖。
代碼部分如下所示:
this.dataSet = this.dataService.getData(this.id);
this.dataSet.subscribe(
x => this.rightData = x.rightCount,
x => this.wrongData = x.wrongCount,
);
console.log('First value: ' this.rightData);
console.log('Second value: ' this.wrongData);
this.pieChartData = [this.rightData, this.wrongData];
它不起作用,控制臺輸出是:
First Value: undefined
Second Value: undefined
但是當我將代碼更改為以下內容時,控制臺日志會顯示正確的資料:
this.dataSet = this.dataService.getData(this.id);
this.dataSet.subscribe(
x => console.log(x.rightCount),
x => console.log(x,wrongCount),
);
輸出:
3
7
附加代碼:
export interface Counter {
rightCount: number;
wrongCount: number;
}
dataSet: Observable<Counter> = of();
該服務如下所示:
getData(id: number): Observable<Counter> {
return this.http.get<Counter>(`/backend/getData?id=${id}`);
}
Firefox 日志顯示我,后端回傳:
{"rightCount":3,"wrongCount":7}
你有我犯錯誤的想法嗎?
uj5u.com熱心網友回復:
這種行為是正常的,因為您的代碼(訂閱)異步運行。這將與以下內容相同:
let test;
setTimeout(() => {this.test = "hello"}, 1000);
console.log(test);
上面的代碼會列印undifined正確嗎?doingsubscribe()類似于 asetTimeout因為兩個代碼都是異步運行的。
如果你愿意的話:
this.dataSet.subscribe(
x => console.log('test1')
);
console.log('test2');
輸出將是:test2 test1因為里面的代碼是subscribe異步的
在您的情況下,正確的代碼是:
this.dataService.getData(this.id).subscribe(
x => {
this.rightData = x.rightCount;
console.log('First value: ' this.rightData);
// this.wrongData is undefined here
this.pieChartData = [this.rightData, this.wrongData];
},
err => {
this.wrongData = x.wrongCount;
console.log('Second value: ' this.wrongData);
// this.rightData is undefined here
this.pieChartData = [this.rightData, this.wrongData];
}
);
請注意,只有在拋出錯誤時才會出現第二個值/錯誤資料this.dataService.getData
uj5u.com熱心網友回復:
您可以將最終操作封裝在訂閱中的“finaly”中。
像這樣的東西
this.dataSet = this.dataService.getData(this.id);
this.dataSet.subscribe(
x => (this.rightData = x.rightCount),
x => (this.wrongData = x.wrongCount),
() => {
console.log('First value: ' this.rightData)
console.log('Second value: ' this.wrongData)
this.pieChartData = [this.rightData, this.wrongData]
}
);
要不就
this.dataService.getData(this.id).subscribe(
x => (this.rightData = x.rightCount),
x => (this.wrongData = x.wrongCount),
() => {
console.log('First value: ' this.rightData)
console.log('Second value: ' this.wrongData)
this.pieChartData = [this.rightData, this.wrongData]
}
);
請注意,“finally”不接收任何引數,它僅用于在從 observable 接收到成功或錯誤后進行操作
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/452434.html
