Victor Lu
Victor Lu

Reputation: 11

How to get value from Promise Object Type in Angular?

I have defined a function call in Angular Service:

getNewJoinerInfo(staffID: String) {
    return this.httpClient.get(this.ldapEndPoint + staffID, this.httpOptions).toPromise()
               .then(res => of(JSON.parse(JSON.stringify(res)).result[0] as NewJoinerObj))
}

When I call this function in a component, how can I get those values from Promise<NewJoinerObj> type? As I try to assign the return to NewJoinerObj type it's wrong as Promise<NewJoinerObj> is not NewJoinerObj.

var response = <NewJoinerObj> this.newJoinerService.getNewJoinerInfo(this.newJoiner.staffId);

What shall I do?

Upvotes: 1

Views: 928

Answers (1)

Owen Kelvin
Owen Kelvin

Reputation: 15083

You are using angular.

Using Promises in angular is not recommended

Lets consider the below code

getNewJoinerInfo = (staffID: String) => 
  this.httpClient.get(this.ldapEndPoint + staffID, this.httpOptions)

I simply return the response. This will return an Observable<Object>. Lets consider your code,

You call .toPromise() - This converts to Promise
You call the .then() and return of() which converts back to Observable

You could have achieved this by simply piping the Observable stream

import { map } from 'rxjs/operators';

getNewJoinerInfo = (staffID: String) => 
  this.httpClient.get(this.ldapEndPoint + staffID, this.httpOptions).pipe(
    map(([result]) => result as NewJoinerObj )
  )

I have used destructuring to extract the first item i.e instead of map((result) => result[0] ) I have map(([result]) => result )

The next thing to note is that you need to subscribe to the Observable. Look at it like the .then() of Observables.

In your component you can have

newjoiner: NewJoinerObj;

ngOnInit () {
this.myService.getNewJoinerInfo().subscribe(
    res => this.newjoiner = res
  )
}

And in your html simply bind

<span>{{ newjoiner | json }}</span>

The json pipe simply enables display of JSON object

Upvotes: 1

Related Questions