-1

My component

export class MoviedetailComponent implements OnInit {
 movie:any

 constructor(
  private getmovie: GetmovieService,
  private router: Router,
  private rout: ActivatedRoute
 ) { }

 ngOnInit() {
   this.rout.params
   .switchMap((params: Params) => 
   this.getmovie.getMovieById(+params['id']))
   .subscribe(movie => {
    this.movie = movie;
    console.log(this.movie);
 });

 }

}

my html

<p>{{movie.title}}</p>

So when I load the page, it shows the content of movie.tittle, but there is also an error in console saying "Cannot read property 'title' of undefined"

Any ideas?

Carl.W
  • 1
  • 3

1 Answers1

0

The subscribe() function is asynchronous, meaning the code inside of the callback (including this.movie = movie) can be executed after the completion of the ngOnInit() method.

As @kirk and @jonrsharpe pointed out in the comments, you could add a test before the value inside of the template. But this is not the most elegant solution.

I would suggest instead reading up on Observables, and in particular, the async pipe. This makes your code a lot simpler:

this.movie = this.route.params
  .switchMap((params: Params) => 
      this.getmovie.getMovieById(+params['id']))

and then your HTML would look like:

<p>{{ (movie | async)?.title }}</a>

Note the ?- this checks that the title property actually exists, so that an error doesn't occur if the object is invalid. You should also add a template block somewhere else which handles cases of errors.

Derek Brown
  • 4,232
  • 4
  • 27
  • 44