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!

3

1 Answer 1

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);});
Sign up to request clarification or add additional context in comments.

1 Comment

Exactly, you should also brush up on RxJS Observers, Luis.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.