-2

I'm trying to get an object from a request but get an error.

user.service.ts:

async obtainUser(user_id: string): Promise<User> {
  return await this.httpClient.get<User>(requestUrl).toPromise().then((res) => {res});
}

user.componenet.ts:

var user = <User>this.userService.obtainUser(user_id);
console.log(user);

The error is:

error TS2352: Conversion of type 'Promise<User>' to type 'User' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
industrialareas_angular_ctnr |   Type 'Promise<User>' is missing the following properties from type 'User': id, fiscal_id, first_name, last_name, and 9 more.

Can anybody help me?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • 1
    If you want the value from a promise, you need to _await_ it. You already seem to know that, because you're using that syntax in the code you've posted. TypeScript's doing exactly what it's supposed to - it's telling you your code is wrong. Also note `toPromise` is deprecated and `.then((res) => {res})` makes that a promise of `undefined`, not the response body.. – jonrsharpe Dec 22 '21 at 00:00
  • Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – jonrsharpe Dec 22 '21 at 00:03

1 Answers1

0

user.service.ts:

obtainUser(user_id: string): Promise<User> {
  return this.httpClient.get<User>(requestUrl).pipe(map(user => new User(user))).toPromise();
}

user.componenet.ts:

const user = await this.userService.obtainUser(user_id);
console.log(user);