Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subscribe Observable value

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));
}
like image 729
Anna Avatar asked Jul 06 '16 10:07

Anna


2 Answers

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.

like image 56
Günter Zöchbauer Avatar answered Oct 17 '22 20:10

Günter Zöchbauer


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')
);
like image 30
Fred Fuchs Avatar answered Oct 17 '22 20:10

Fred Fuchs