Issue
I'm new to Angular 12 framework. I'm following a tutorial that uses the Observable
class to query on fixed data asynchronously; I'm getting ts(2322)
error due to version differences caused by using Angular 8 in training. A summary of the service, module and data source is available below:
/* movie.service.ts */
export class MovieService
{
...
getMovie( id: number ) : Observable<Movie>
{
/* TS(2322) error occurs in the following line of code. */
return of( Movies.find( movie => movie.id === id ) );
}
}
/* movie.datasource.ts */
import { Movie } from "./movie";
export const Movies: Movie[] = [
{ id: 1, name: "movie1", imageUrl: "1.jpg" },
{ id: 2, name: "movie2", imageUrl: "2.jpg" }
];
/* movie.ts */
export class Movie
{
id!: number;
name!: string;
imageUrl!: string;
}
The getMovie()
method in file movie.service.ts
outputs the following error:
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'.ts(2322)
I'm aware that this problem is caused by type-safe rules of TypeScript. How can I solve this problem?
Thank you in advance for your help.
Solution
Well, the error is self-describable. Movies.find()
can return a movie if found or undefined
otherwise. The simplest way to accommodate is to expect exactly that:
getMovie( id: number ) : Observable<Movie | undefined>
{
return of( Movies.find( movie => movie.id === id ) );
}
Alternatively, you can check for result of find()
, and if it is null - return a new Movie()
or throw exception
Answered By - Felix
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.