1

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.

Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203
Emad joha
  • 97
  • 1
  • 1
  • 10
  • If you send an email, and then, immediately after, try to print the response to that email, will that print anything? Same here. You can't print a response to a request before the response has come back. – JB Nizet Sep 14 '18 at 19:21
  • I'm try to get data outside Observable like this in link : https://stackoverflow.com/questions/41945817/observable-undefined how can me to get data from outside ? – Emad joha Sep 14 '18 at 19:27
  • You can't. The data is available inside the callback, and you can call any other method you want from that callback. – JB Nizet Sep 14 '18 at 19:28

1 Answers1

0

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)
}
lietutis
  • 201
  • 1
  • 12