2

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?

18
  • 2
    You should terminate your statements with ; character. Example: this.messageService.add("Movie Was Successfully added!"); Commented Mar 2, 2018 at 14:21
  • 3
    @Igor no. using ; is NOT mandatory - i never use them Commented Mar 2, 2018 at 14:26
  • 2
    @messerbill Take a look to this stackoverflow.com/a/1169596/5119765 Commented Mar 2, 2018 at 14:32
  • 1
    @ADreNaLiNe-DJ yes this is true - therefor you are right. But i always write my code inside of "framework given structures" (like express and angular) - so i nearly never come to this case! But i forgot it! Thank you very much Commented Mar 2, 2018 at 14:35
  • 1
    I could see that possibly movieService.getMovie might not fire if this returns an observable that you do not subscribe to. I do not see how console.log statements would never appear in the browser though if you add them in your callback in setTimeout. Did you add a log statement before the setTimeout and one inside the setTimeout to see if at least one of those appears? Commented Mar 2, 2018 at 14:36

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

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.