繁体   English   中英

认购可观察回报未定义

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM