从REST API获取值后,在angular js中的subscribe内返回值undefined

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

这是REST API返回的数据

{

    "clo_change": 91.0,
    "vam_change": 72.76,
    "sla_change": 94.0,
    "feedback_change": 87,
    "so_change": 69.0,
    "cost": 87277.75

}

在我的service.ts文件中,我正在向URL发出请求

public getNewPlanData(): Observable<any>{
console.log("I am here createNewPlanModel");
    return this.http.get('http://localhost:8000/newplandata/')
        .map((response: Response) => {
         console.log("I am here createNewPlanModel2");
         return response.json()
        });
  }

我订阅了component.ts文件中的observable

this.mainService.getNewPlanData().subscribe(result =>{ 
      console.log("inside subscribe")
     this.newData=result;    
     console.log(this.newData)         
     }, error => console.log(error));  
    console.log("outside subscribe")

当我在Chrome中调试代码时,第一次没有命中应用程序

值未定义,并打印“外部订阅”

并且在第二次我从REST API获取值并且值在subscribe循环中打印但是它没有进入console.log("outside subscribe")的下一个语句而是抛出错误

返回值:未定义

并且这些值不用于进一步处理。

我希望在subscribe循环外使用this.newData值进行进一步处理。请帮我解决一下。

angular subscribe
1个回答
0
投票

您可以在这种情况下使用超时,这可能在某种程度上有所帮助。

  setTimeout(() => {
      this.mainService.getNewPlanData().subscribe((result) => {
        console.log('inside subscribe');
        this.newData = result;
        console.log(this.newData);
      },
        (error) => {
          console.log(error);
        });
    }, 1000 );
    console.log('now I will have data '+this.newData);
© www.soinside.com 2019 - 2024. All rights reserved.