Subscribe not working even in NgZone.run()

662 views Asked by At

I read articles on how to use NgZone in angular. But still I'm not able to enter subscribe in the first call of execution. Please help me with this. Thanks in advance :)

 constructor(private _apicallservice: ApiCallService, private _ngzone : NgZone) {
  this.someMethod();
})

}

  ngOnInit() {
    this.someMethod();
  }

Method I want to execute:

  getEVforMetric() {
  this._apicallservice.getData("report/getmetricIsEVdata").subscribe(data => {
    console.log("EV values returned from API");
    this.isSchVarByReleaseDate = data[0].Value;
    this.isCostVarianceByEv = data[1].Value;
  })
}

I have a service which gets the data from API. Data is getting returned from API but subscribe is not working in the first call and I'm getting both values as undefined. I understood it is because of Asynchronous call in Angular so I wrapped my method inside NgZone like this but nothing seems to work out.

     someMethod() {
      this._ngzone.run(() => this.getEVforMetric())
     }

I did console.log for both the values but they are coming as undefined in the first call but after some other method executions data is subscribed. I want these values to get updated in the first call itself. I'm a beginner in Angular please help out :)

getData() Method:

getData(url: string){
    let pagedata: any;
    var data = JSON.parse(this._clientcacheservice.getPageCache(PageDataEnum.userInfo));
    let jsonObj: any = data.defaultfilter;
    jsonObj.userId = data.userid;
    let Url = environment.apiUrl + '/api/' + url ;
    pagedata = this.post(Url, jsonObj);
    return pagedata;
}
1

There are 1 answers

6
Rahul Cv On

Your get data method is not returning any observable Kindly update it

getData(url: string){
        let pagedata: any;
        var data = JSON.parse(this._clientcacheservice.getPageCache(PageDataEnum.userInfo));
        let jsonObj: any = data.defaultfilter;
        jsonObj.userId = data.userid;
        let Url = environment.apiUrl + '/api/' + url ;
        pagedata = this.post(Url, jsonObj);
    return new Observable<string>(observer => {
pagedata.subscribe(response=>{
    observer.next(response);
})
     
      });
        
    }