Angular 4: Class with constructor as http Observable model

后端 未结 1 621
无人及你
无人及你 2020-12-18 14:27

In my app, I have a model defined as Class with a constructor. Like this:

export class Movie {
    title: string;
    posterURL: string;
    description: str         


        
相关标签:
1条回答
  • 2020-12-18 14:56

    HttpClient methods are generic, this.http.get<Movie[]> asserts that the result conforms to Movie[] interface and doesn't create Movie instances.

    In order for the result to become class instances, the class should be explicitly instantiated. Class constructor should preferably accept plain object which properties will be assigned to class instance, and Movie already does this with cfg parameter.

    Since it's unlikely that Partial<Movie> type precisely describes the interface, it's better to declare a separate interface:

    interface IMovie {
        title: string;
        posterURL: string;
        description: string;
    }
    
    class Movie implements IMovie { ... }
    
    ...
    
    getMoviesData(): Observable<Movie[]> {
        return this.http.get<IMovie[]>(...)
        .map(plainMovies => plainMovies.map(plainMovie => new Movie(plainMovie)))
    }
    
    0 讨论(0)
提交回复
热议问题