Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

typescript - Angular 4: Class with constructor as http Observable model

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

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

    public constructor(cfg: Partial<Movie>) {
        Object.assign(this, cfg);
    }

    getEndDate(): Date {
        return new Date();
    }
};

I also have an HTTP request that uses this model

getMoviesData(): Observable<Movie[]> {
    return this.http.get<Movie[]>(`http://localhost:3544/movies`)
}

As expected, it doesn't work

How can I solve this? Should I also create an interface or what?

Thanks for the help :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)))
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

62 comments

56.5k users

...