我使用一个服务来用后端的数据填充我的可观察对象.后端正在删除正确的数据.现在我想获取可观测值,并建立一个图表.

代码部分如下所示:

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

但当我将代码更改为以下内容时,控制台日志(log)会显示正确的数据:

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日志(log)显示,后端返回:

{"rightCount":3,"wrongCount":7}

你知道我哪里出错了吗?

推荐答案

这种行为是正常的,因为您的代码(订阅)是异步运行的.这与:

let test;
setTimeout(() => {this.test = "hello"}, 1000);
console.log(test);

上面的代码可以打印undifined,对吗?

如果你愿意:

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中抛出错误时,才会出现第二个值/错误数据

Typescript相关问答推荐

TypScript中的算法运算式

如何修复正在处理类型但与函数一起使用时不处理的类型脚本类型

Next.js错误:不变:页面未生成

如何在TypeScrip中正确键入元素和事件目标?

Cypress页面对象模型模式.扩展Elements属性

如何使所有可选字段在打印脚本中都是必填字段,但不能多或少?

寻址对象中路径的泛型类型

是否将自动导入样式从`~/目录/文件`改为`@/目录/文件`?

在列表的指令中使用intersectionObservable隐藏按钮

在VSCode中显示eslint错误,但在终端中运行eslint命令时不显示?(Vite,React,TypeScript)

在React中定义props 的不同方式.FunctionalComponent

如何创建由空格连接的多个字符串的类型

将对象的属性转换为正确类型和位置的函数参数

当传递带有或不带有参数的函数作为组件props 时,我应该如何指定类型?

如何静态键入返回数组1到n的函数

重写返回任何

如何创建由一个帐户签名但使用另一个帐户支付的Hedera交易

仅当定义了值时才按值筛选数组

React HashRouter,单击导航栏时页面重新加载出现问题

带有 Select 器和映射器的Typescript 泛型