Subscribe to observable is returning undefined

后端 未结 6 698
面向向阳花
面向向阳花 2020-12-01 07:27

So I am trying to subscribe to a simple service that return data from a local JSON file.

I have managed to get the service working, I can log it out in the function

相关标签:
6条回答
  • 2020-12-01 07:30

    Maybe some pictures help?

    The numbers here indicate the order of operations.

    Send the Http Request

    1. Component is initialized and calls the getMovies method of the movieService.
    2. The movieService getMovies method returns an Observable. NOT the data at this point.
    3. The component calls subscribe on the returned Observable.
    4. The get request is submitted to the server for processing.
    5. The ngOnInit method is complete.

    Any code here after the subscribe cannot access the movies property since the data has not yet been returned.

    Receive the Http Response

    At some LATER point in time ...

    1. The movies are returned to the service.
    2. If the process was successful, the first callback function is executed.
    3. The local movies property is assigned to the movies returned from the service. It is only here that the movies property is finally set.

    Attempting to access the movies property prior to step #8 results in an error.

    Can we access the value here? NO

    To fix it:

    0 讨论(0)
  • 2020-12-01 07:31
    objResponse;
    this.service.getData().subscribe((result: any)=> { 
    this.objResponse=result;
    }
    

    Returning something won't required

    0 讨论(0)
  • 2020-12-01 07:44

    you can do it like this:

    In your app-component:

    public getDataFromService() {
      this._api.getData(this);
    }
    
    
    public setData(data: any){
     this.data=data;
    }
    

    In your service/api.ts:

    public getData(obj: appComponentModel){
        this.http.get(url).subscribe(res => obj.setData(res));
    }
    
    0 讨论(0)
  • 2020-12-01 07:47

    You've got a problem between sync and async function. You'r issue is: getDateFromService is syncronous and the content inside is async. So when the ngOnInit function call getDataFromService, you'r code don't wait the async task. you'r getDataFromService need to return an observer or need to implement the return of your API (you need to choose).

    public ngOnInit(): void {
      console.log(this.getDataFromService().subscribe(data => console.log(data)); // This return undefined
    }
    
    public getDataFromService() {
      return this._api.getData();
    }
    
    0 讨论(0)
  • 2020-12-01 07:48

    Try with:

    getData(): any {
           return this._http.get('api.json');
    }
    

    or

       getData(): any {
               return this._http.get('api.json').map((response: Response) => { 
        response.json();
    })
    
    0 讨论(0)
  • 2020-12-01 07:55

    Instead of logging at the ngOnInit() method as you did

     public ngOnInit(): void {
          console.log(this.getDataFromService()); // This return undefined    }
    

    log inside the subscribe() method as

    export class AppComponent {
      public data: any
      public informationData;
    
      constructor(private _api: ApiService) {}
    
      public ngOnInit(): void {
        this.getDataFromService(); //don't log here, logging here will return undefined
      }
    
      public getDataFromService() {
        this._api.getData().subscribe(response => {
          this.informationData = response;
          console.log(this.informationData); //log here, like this
          return this.informationData;
        });
      }
    }
    
    0 讨论(0)
提交回复
热议问题