简体   繁体   中英

return proper object from angular http.get with promise

I have a http get function which grabs the data structure, but I really would like to have the actual object (I have functions on it).

public async get(guid: string): Promise<PctLayer>
{
    return await this.http.get<PctLayer>(`${this.url}/${guid}`, { headers: this.header }).toPromise();
}

I can solve that by

let layer = Object.assign(new PctLayer(), await this.layerService.get(info.id));

which does the job nicely. Is there a way to move the Object.assign into the async get? I couldn't get it to work together with the Promise, ie I'm not sure how to still return a Promise when I call Object.assign in the async get.

I know there's different solution rather than using Object.assign, but they involve a whole lot more code, and I like to keep code short and simple to use.

return await this.http.get<PctLayer>(`${this.url}/${guid}`, { headers: this.header })
.map(r => {
  Object.assign(new PctLayer(), r);
})
.toPromise()

May work for you. Just include Object.assign inside observable chain, before mapping it to promise

Edit

Because I'm form RxJS 5 era, below is 6.x version as well:

return await this.http.get<PctLayer>(`${this.url}/${guid}`, { headers: this.header })
.pipe(map(r => {
  Object.assign(new PctLayer(), r);
}))
.toPromise()

One more edit

On my presonal projects, when I need to inject data from HTTP fetch to an object, I'd usually just construct new object with REST-response as input parameter:

export interface MyClassInterface {
  A: string;
}
export class MyClass implements MyClassInterface{
  public A: string;
  constructor(iIn: MyClassInterface) {
    this.A = iIn.A
    /* and so on */
  }
  public myUsefulFinction() { /*Do stuff*/ }
}

Then assuming, that GET-response is compatible with interface, you can just

return await this.http.get<PctLayer>(`${this.url}/${guid}`, { headers: this.header })
.pipe(map(ifc => MyClass(ifc)))
.toPromise()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM