Angular 7:将从observable返回的对象值赋给变量

问题描述 投票:0回答:1

我试图将返回值从服务分配给组件时遇到问题。

  ngOnInit() {
    this.getInspectionData();
  }

  getInspectionData() {
    this.auctionService.getInspectionResult(`df570718-018a-47d8-97a2-f943a9786536`)
      .subscribe(data => {
        console.log(`this is data returned: `, data);
      }, error => {
        console.log('failed to get data', error);
      }, () => {
        console.log('getInspectionResult successfully processed');
      });
  }

它成功地在console.log中获得了返回值

console.log result

subscribe()内。似乎没有问题。甚至我将console.log设置为subscribe()中的变量:

  .subscribe(data => {
    this.inspectionResult = data;
    console.log(`value from getInspectionData: `, this.inspectionResult);

它正确地给了this.inspectionResult输出。

它应该是正确的,对吗?然后我添加this.inspectionResult = data;

但....

当我测试它时,变量出错,它得到'{}'。代码如下:

  ngOnInit() {
    this.getInspectionData();
    console.log(`value from getInspectionData: `, this.inspectionResult);
  }

  getInspectionData() {
    this.auctionService.getInspectionResult(`df570718-018a-47d8-97a2-f943a9786536`)
      .subscribe(data => {
        this.inspectionResult = data;
      }, error => {
        console.log('failed to get data', error);
      }, () => {
        console.log('getInspectionResult successfully processed');
      });
  }

this is the result

顺便说一句,我已经分配了这样的变量:

  inspectionResult: InspectionResult = <InspectionResult>{};
  inspectionResultData: InspectionResultData = <InspectionResultData>{};

我的问题是:

  1. 为什么数据值没有分配给qazxsw poi?
  2. 为什么ngOnInit()没有给出我期望的输出方式? (this.inspectionResult中的console.log()应该在ngOnInit()之后运行)
angular typescript frontend angular-httpclient
1个回答
0
投票

可能是由于

this.getInspectionData(); console.log(getInspectionData();,this.inspectionResult);

在这种情况下,this.getInspectionData()可能会延迟此过程。但是在完成上述方法之前,console.log()已经开始了。

你必须等待方法完成。请参考,你会得到一些清晰度

value from getInspectionData:

© www.soinside.com 2019 - 2024. All rights reserved.