0

I'm trying to retrieve data from and endpoint in Angular. This is the service:

export class VideosService {
result;
constructor(private http: Http, public router: Router) { }

getVideos() {
    this.http.get('http://localhost:3000/videos?sessionId=' + localStorage.getItem('sessionId'))
        .map(response => response.json())
        .subscribe(result => this.result = result);
        localStorage.setItem('videos', this.result);
        console.log(localStorage);
}

It works everytime EXCEPT the first one. The first one I've got "undefined" and the other one's I get the actual object.

What I'm doing wrong? Thnks!

  • *the other one's I get the actual object* No, you get the **previous** object. –  Jul 17 '17 at 02:53
  • Yes I can see it now. Thank you sir – Luis Matias Pierdona Jul 17 '17 at 03:54
  • Possible duplicate of [How do I return the response from an Observable/http/async call in angular2?](https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular2) – AT82 Jul 17 '17 at 09:15

1 Answers1

2

In your code:

.subscribe(result => this.result = result);
localStorage.setItem('videos', this.result);

The code localStorage.setItem('videos', this.result); will execute before .subscribe(result => this.result = result);.

Fix

Lookup async programming JavaScript or simply:

.subscribe(result => {this.result = result;   localStorage.setItem('videos', this.result);});
basarat
  • 261,912
  • 58
  • 460
  • 511