简体   繁体   中英

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

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);
});

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

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