Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Where am I making a mistake in my angular code?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading