[英]Subscription of observable returns undefined
我使用一項服務用來自后端的數據填充我的可觀察對象。 后端正在傳遞正確的數據。 現在我想獲取 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];
它不起作用,控制台 output 是:
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),
);
Output:
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}
你知道我在哪里犯了錯誤嗎?
這種行為是正常的,因為您的代碼(訂閱)是異步運行的。 這將與以下內容相同:
let test;
setTimeout(() => {this.test = "hello"}, 1000);
console.log(test);
上面的代碼會打印undifined
對嗎? 執行subscribe()
類似於setTimeout
,因為這兩個代碼都是異步運行的。
如果你願意的話:
this.dataSet.subscribe(
x => console.log('test1')
);
console.log('test2');
output 將是: 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
中拋出錯誤時才會出現第二個值/wrongData
您可以將最終操作封裝在訂閱的“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”不接收任何參數,它僅用於在從可觀察對象接收到成功或錯誤后進行操作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.