角度7:将可观察到的对象值分配给变量

时间:2019-02-13 08:47:03

标签: angular typescript frontend angular-httpclient

我在尝试将服务的返回值分配给组件时遇到问题。

  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. 为什么数据值没有分配给this.inspectionResult
  2. 为什么ngOnInit()没有给出我期望的输出方式? (console.log()中的ngOnInit()应该在getInspectionData();之后运行)

1 个答案:

答案 0 :(得分:0)

可能是由于

this.getInspectionData(); console.log(value from getInspectionData:,this.inspectionResult);

在这种情况下,this.getInspectionData()可能会延迟。 但是在上述方法完成之前,console.log()令人兴奋。

您必须等待方法完成。请参考此内容,您将会有所了解

http://www.damirscorner.com/blog/posts/20170127-Angular2TutorialWithAsyncAndAwait.html