Home > Net >  How to retrieve data using firstValueFrom - Angular 13?
How to retrieve data using firstValueFrom - Angular 13?

Time:03-17

In my userService, I have:

async getUserData() {
    const user = await this.afAuth.currentUser;
    const token = await user?.getIdToken();
    const headers = { Authorization: `Bearer ${token}` };
    const url = "...";
    const response = await firstValueFrom(this.http.get(url, { headers }));
    return response;
  }

and in my ngOnInit of a certain component I have:

ngOnInit(): void {
    this.user.getUserData().then((res) => console.log(res));
  }

I can log the returned object ok, I see its properties, but I have no idea why I cannot access the property data of it. I can only access constructor, hasOwnProperty, isPrototypeOf, etc...

Does anyone know what I am doing wrong? Thanks a lot in advance.

CodePudding user response:

How about using plain rxjs for the job instead of mixing promises in there?

When using angular, the best approach is to surrender to Observables.

You could change your service function to

getUserData() {
    ...
    return this.http.get(url, { headers }))
  }

and in your component:

ngOnInit() {
    this.user.getUserData().pipe(take(1)).subscribe(res => 
    {
      console.log(res))
    });
  }

CodePudding user response:

You did not type the get request like this:

this.http.get<MyDataStructure>(url, { headers })

If you do not type it, the signature of get will be: Observable<Object>.

If you do type it with T it will be Observable<T>.

So the data is actually there. TypeScript just does not know it is there and thus the IDE does not give the respective hints.

If you do not want to define the type specifically you can use this.http.get<any>(url, { headers }) to work around it.

  • Related