Subscribe to observable is returning undefined

后端 未结 6 708
面向向阳花
面向向阳花 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: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();
    }
    

提交回复
热议问题