Mathieu Landry
Mathieu Landry

Reputation: 13

Create Object from HttpClient

When using httpclient you can give the type to the get call and receive a struct of that object. For instance.

http.get<ProductData>("url:ressource:id").subscribe(x=> this.myObj = x)

this leads to having myObj only appear to be the type of the object. If i have functions on that obj they arent callable. I know from there that i should create a new Object and assign the properties of the result of the request to the new Object. My question is, is it possible to have a function that takes a type as Template and then returns an observable of that type with an instance ?

something like this http.get<ProductData>("url:ressource:id").makeNew<Product>() here the result of makeNew would be observable of type Product and then if you subscribe to it, You would get a Product.

I think the simplier way to think about it is. From this exemple.

this.http
.get<IProduct>('https://dummyjson.com/products/1')
.pipe(
  map((x) => {
    var a = new ProductDisplay();
    Object.assign(a, x);
    return a;
  })
)
.subscribe((x) => {
  console.log('obj is ', x);
});

Is it possible to replace the .map portion with one function call like makeNew<Product>()

Upvotes: 0

Views: 467

Answers (1)

Andrei
Andrei

Reputation: 12021

you could make your own operator which would create instances of a class for you

export const makeNew = <T>(clazz: new () => T) => map(x => Object.assign(new clazz(), x));

and use it as one liner in your pipe

...
get<...>(...).pipe(
  makeNew(ProductDisplay)
)

Upvotes: 2

Related Questions