Subscribe Observable value

2020-04-08 01:46发布

问题:

When I'm logging the value of my variable inside the subscribe i have a value but when doing it outside it i get undefined ???:

this._postService.getConf("app/conf/conf.json")
   .subscribe(res =>{
      this.home = JSON.stringify(res);
      console.log("value :" + this.home);

i want to initialize my home variable with a certain value I'm doing it on ngOnInit but it get the value undefined when I'm trying to get it outside:

This is my function :

getConf(url) {
   return this._http.get(url).
      map(res => {return res.json()});
}

ngOnInit() {

  this._postService.getConf("app/conf/conf.json")
   .subscribe(res => {
        this.home = JSON.stringify(res);
        console.log("hahowaaaaaaaa" + this.home);
   }
  );

  this._postService.getPosts(this.home)
  .subscribe(result =>{ 
    this.loading = false;
    this.actionsG = result; 
    var count = JSON.stringify(result);

    this.aCount = count.substring(count.indexOf(','),23);

  },error=> console.error('Error: ' + error), ()=> console.log('finish! ActionsG'));

  this._postService.getPosts(this.home ).subscribe(result => this.actionsV = 
    result, error=> console.error('Error: ' + error), ()=> console.log('finish! ActionsV ngOnInit' + this.page));
}

回答1:

That's how observables work. When the response from the server arrives, the callback passed to subscribe(...) is called by the observable.

The console.log() outside of subscribe() is executed before the call to the server is even made.



回答2:

My ngOnInit() had called a process that gets data from a DB. I expected the this.## variables which were updated in the method to be available after the call. As was described above, the call passes to observable, which means the variables are not available in ngOnInit(). But they were all populated when the HTML page displayed.

So the solution is to do all the needed work inside the method and then refer to variables which will be populated in HTML.

this.service.getCity(zip).subscribe(
    data => {
        if (data.errStatus == 0) {
            console.log("data: " +   data.xx.List);

            this.xx.List = data.xx.List;
            console.log("data2: " + this.xxList);
        } else {
            data.errText;
            console.log(data.errText);
        }
    },
    err => console.error(err),
    () => console.log('done')
);