Search code examples
angulartypescriptsubscribe

why print undefined data out of Observable in angular 2


My code in service is:

getUserdata(id:string): Observable<any> {
    return this.http.get('https://jsonplaceholder.typicode.com/todos/' + id)
        .map((res: Response) => {
            const data = res.json();
            return data;
        })
}

And in my component is:

ngOnInit() {
    this.serveicService.getUserdata('1').subscribe(res => {
        this.title = res.title; 
        console.log(this.title); // prints value   
    });
    console.log(this.title); // prints undefined 
}

I need to get data outside of the subscribe method.


Solution

  • Everything seems correct. Your method 'getUserdata' returns Observable which means that you will get your value only when it gets that new value after time X. Thats why your second print returns undefined -> 'getUserdata' hadn't returned Observable.

    If you want to change/work with data which is returned, then you should do everything when data is returned (in subscribe).

    If you want to use it in html, feel free to assign them in .subscription() block and use in html, but for a short period of time (unless it fails/lags) you wouldn't see/use them (they would be undefined, because you are still waiting for data to be fetched)

    how to use:

    ngOnInit() {
        this.serveicService.getUserdata('1').subscribe(res => {
            this.title = res.title; 
            console.log(this.title); // prints value   
            // here we have our data and we can start work with it
        });
        console.log(this.title); // prints undefined (can't work with it, because it's async, you don't have value here)
    }