Angular 2 return data from service is not availabe after RxJs subscribe

后端 未结 2 875
时光取名叫无心
时光取名叫无心 2021-01-06 23:15

In my map.service I have coded like this

loadAdminDataDiv (): Observable {
     return this.http.get(\"static/data/data.json\")
                          


        
相关标签:
2条回答
  • 2021-01-06 23:46

    Here I got another way... I used static keyword for solving this problem...

    getSubscribeData: any;
    getAllvaluesFromFiles() {
    this._mapService.loadAdminDataDiv().subscribe(data => {
          this.getSubscribeData = data;
          YOUR_CLASSNAME.setSubscribeData(data);
        },
        error => { console.log(error) },
        () => {
            console.log(this.getSubscribeData);  // prints the data 
          }
        );
    }
    ngAfterContentInit() {
    this.getAllvaluesFromFiles();
     console.log(this.getSubscribeData); // prints Undefined
     console.log(YOUR_CLASSNAME.subscribeData); // prints
    }
    
    static subscribeData:any;
    static setSubscribeData(data){
       YOUR_CLASSNAME.subscribeData=data;
    }
    

    try to use this ... hope this will help you

    0 讨论(0)
  • 2021-01-07 00:09

    In this code

      ngAfterContentInit() {
        this.getAllvaluesFromFiles();
        console.log(this.getSubscribeData); // prints Undefined
      }
    

    console.log(this.getSubscribeData) is actually before subscribe

    subscribe() schedules an async call for Http to make when the current sync thread of execution is completed.
    Then your console.log(...) is executed.
    When then eventually the response from the server arrives, the callback you passed to subscribe(...) is executed.

    To be able to execute some code when the response arrived you can use for example

      getAllvaluesFromFiles() {
        return this._mapService.loadAdminDataDiv()
        .do(data => {
          this.getSubscribeData = data;
        })
        .do(() => {
            console.log(this.getSubscribeData);  // prints the data 
        })
        .catch(error => { 
            console.log(error);
            throw error;
        });
      }
    

    This way an Observable is returned

      ngAfterContentInit() {
        this.getAllvaluesFromFiles()
        .subscribe(data => {
          console.log(this.getSubscribeData); 
        })
      }
    

    This way the calls are properly chained so that console.log(...) is executed after the data is available.

    0 讨论(0)
提交回复
热议问题