Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
57
rated 0 times [  64] [ 7]  / answers: 1 / hits: 18130  / 6 Years ago, sun, may 27, 2018, 12:00:00

I have a question about the Angular 5 httpClient.



This is a model class with a method foo() I'd like to receive from the server



export class MyClass implements Deserializable{
id: number;
title: string;

deserialize(input: any) {
Object.assign(this, input);
return this;
}

foo(): string {
// return some string conversion with this.title
}
}


This is my service requesting it:



import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { MyClass } from './MyClass';

@Injectable({
providedIn: 'root',
})
export class MyClassService {

constructor(private http: HttpClient) {
}

getMyStuff(): Observable<MyClass[]> {
// this is where I hope to convert the json to instances of MyClass
return this.http.get<MyClass[]>('api/stuff')
}
}


My Problem



When I ask the service for instances of MyClass I get the data, but I cannot run {{ item.foo() }} in the template. Also, when I console.log() the typeof of an item where it is received in the service, I do no see instances of an object of MyClass.



What am I doing wrong? I thought that writing this.http.get<MyClass[]>('api/stuff') would do the conversion.



Any hints? Thank you in advance!


More From » angular

 Answers
-1

When doing that, TypeScript only does type assertion. It means that you're telling TypeScript that your object is of type MyClass, but the object isn't actually an instance of MyClass at runtime. In order to call functions defined in your model object, you have to define constructors in your model classes like that :



constructor(obj?: any) {
Object.assign(this, obj);
}


Then in your services add a mapping like this :



http.get<MyClass>('/my-class').pipe(
map(res => new MyClass(res))


Note: the code above is RxJS 6 style, i don't know which version you are using


[#54339] Wednesday, May 23, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ramiro

Total Points: 431
Total Questions: 96
Total Answers: 105

Location: Northern Ireland
Member since Mon, Nov 14, 2022
2 Years ago
ramiro questions
Thu, May 7, 20, 00:00, 4 Years ago
Tue, Apr 28, 20, 00:00, 4 Years ago
Sun, Feb 16, 20, 00:00, 4 Years ago
;