Home > other >  Where am I making a mistake in my angular code?
Where am I making a mistake in my angular code?

Time:10-23

Here is my Angular code.

import { Injectable } from '@angular/core';
import { Movie } from './movie';
import { Movies } from './movie.datasource';
import { Observable, of } from 'rxjs';
import { LoggingService } from './logging.service';



@Injectable({
  providedIn: 'root'
})
export class MovieService {

  constructor(private loggingService: LoggingService){}

  getMovies(): Observable<Movie[]> {
    this.loggingService.add('MovieService: Listing movies');
    return of(Movies);
  }

  getMovie(id): Observable<Movie> {
    return of(Movies.find(movie=> movie.id === id));
  }
}

I'm facing this error.

Error: src/app/movie.service.ts:24:5 - error TS2322: Type 'Observable<Movie | undefined>' is not assignable to type 'Observable<Movie>'.
  Type 'Movie | undefined' is not assignable to type 'Movie'.
    Type 'undefined' is not assignable to type 'Movie'.

24     return of(Movies.find(movie=> movie.id === id));

Where am I doing wrong? it was working in the course I was watching but it didn't work when I wrote it myself.

CodePudding user response:

of(Movies.find(movie=> movie.id === id))

Will sometimes return undefined so the real return type of the getMovie method is Observable<Movie | undefined> but you have the return type set to just Observable<Movie>.

Change the return type to Observable<Movie | undefined> and it should work

  • Related