Reputation: 18941
So, it appears I have some great misunderstanding with Typescript
Considering these code snippets, I would expect a method getTitle()
on the returned observable, but it is not there. I simply have an object that looks like AttachabeContentModel
without that method. What gives?
export class AttachableContentModel extends AbstractPopupModel {
Url: string;
EmailAddress: string;
StreetViewUrl: string;
Images: Array<ImageModel>;
Videos: Array<VideoModel>;
Documents: Array<DocumentModel>;
getTitle(): string {
if (this.Name &&
this.DisplayName &&
this.Name !== this.DisplayName)
return this.Name + " (" + this.DisplayName + ")";
return this.Name ? this.Name : this.DisplayName;
};
Silly: string;
}
...
fecthAttachableContent(request: AttachableContentRequest): Observable<AttachableContentModel> {
return this.http
.postAsJson(`${environment.apiBaseUrl}attachablecontent`, {})
.map(res => res.json())
}
Upvotes: 0
Views: 61
Reputation: 31803
Use an interface
, not a class
. Trying to deserialize JSON objects into classes cannot be done without manually calling class constructors. Simply assigning to, or returning as, a compatible type has no effect on run time behavior.
Someone suggested this is a duplicate of another question but the answer that question is very poor because it suggest you follow very poor coding practices.
Even if you do manually call the class constructor, your data is not going to be isomorphic. Keep the logic out of your response and request types.
You should describe the shape of the objects retrieved and sent via HTTP requests with interfaces.
The reason for this is that an interface is just a type and the deserialization function, here .json
, has already created the value for you so you just need to "cast" it. That's actually what you are currently doing, but since the type you're casting to corresponds to a class, it is misleading since the objects created by the deserializer are not instances created by your class constructor.
Please remember to take the Angular 2 documentation examples with a grain of salt as they relate to use of TypeScript. They do not use the language well and are not idiomatic.
Upvotes: 1