kim
kim

Reputation: 31

http toPromise return an object

I have the function below:

getUser(userId: string) : Observable<any> {
    var getUserURL = `/api/users/${userId}`,
        getUserStatus = this.getUserStatus();


    return this.http.get<any>(getUserURL).pipe(
      catchError(this.handleError('getUser - Get User failed', null))
    );
  }

This returns the data from response from REST API for this URL /api/users/${userId} to toPromise

Is there any way that I can return the object that include the response data from REST API + local data(getUserStatus) which is Boolean in this case. Thanks

Upvotes: 1

Views: 1302

Answers (2)

Melchia
Melchia

Reputation: 24224

Like @mtputlz said you're returning an Observable. If you want to return your reponse which is in your case a boolean. Then we can convert the obserable to a promise:

async getUser(userId: string) : any {
    var getUserURL = `/api/users/${userId}`,
        getUserStatus = this.getUserStatus();


    return await this.http.get<any>(getUserURL).pipe(
      catchError(this.handleError('getUser - Get User failed', null))
    ).toPromise();
  }

Upvotes: 0

mtpultz
mtpultz

Reputation: 18248

Your request is not returning a Promise unless it isn't included in your example. You have an Observable.

Assuming I understand your question correctly. If you want to return the HTTP response + the local status you would do something like this using piped operators:

Service

getUser(userId: string) : Observable<any> {
  const path = `/api/users/${userId}`
  const userStatus = this.getUserStatus();

  return this.http.get<any>(path)
    .pipe(
      map((response: any) => {
        return { response, userStatus };
      }),
      catchError(this.handleError('[USER]::getUser Failed', null))
    );
}

Component

this.getUser(1000).subscribe(({response, userStatus}) => { 
  // Handle response and status
  console.log('RESPONSE', response);
  console.log('USER_STATUS', userStatus);
});

Upvotes: 2

Related Questions