Stephen Agwu
Stephen Agwu

Reputation: 1023

setTimeout not working in Angular 5

I pretty sure this is a dumb question which is why I can't find the answer (or at least I hope it is a dumb quesiton with a quick answer). For some reason setTimeout is not working in one of my Angular 5 components. The relevant code looks like this:

onSubmit(...movieData) {
    this.movieService.addMovie(movieData)
        .subscribe(
            movie => {
                this.messageService.add("Movie Was Successfully added!")
                let title = movie['title'], year = movie['year']
                setTimeout(() => {
                    this.movieService.getMovie(title, year);
                }, 5000)
            },
            error => {
                console.log(error)
                this.messageService.add(error.error)
            }
        )
  }

As you can see from the code I'm trying to add a some movie data to a database. If the movie is successfully added I want to display a message for 5 seconds and the using setTimout, navigate to another page (Edit using the this.movieService(title, year) call End Edit). Well the message is displayed but nothing within the setTimeout function is run. I've even added console.log's before and within the setTimeout to confirm its the setTimeout thats not running. Anyone know what I'm doing wrong?

Upvotes: 2

Views: 3788

Answers (1)

Igor
Igor

Reputation: 62298

movieService.getMovie might not fire if this returns an observable that you do not subscribe to. This is because most of the Observables returned from HttpClient are cold observables that do not execute until they are subscribed to.

See also HttpClient - Always subscribe

Upvotes: 1

Related Questions