0

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

2
  • It sounds like you need to instantiate a new object, say x => this.myObj = new Product(x) Commented Dec 11, 2022 at 21:55
  • yes and no. I do but am looking for another solution Commented Dec 11, 2022 at 22:00

1 Answer 1

2

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)
)
Sign up to request clarification or add additional context in comments.

1 Comment

yeah that what i ended up doing

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.