Ionic 如何从一个可观察的仓库中取出物品

hwamh0ep  于 2022-12-08  发布在  Ionic
关注(0)|答案(1)|浏览(127)

I'm trying to build an API service in Ionic with Angular to handle the calls to my API.
I'm using Bearer tokens, and have set the token in storage. I now need to get that token to make API calls.
I'm retrieving the token in the constructor

this.authService.fetchToken().then(token => {
 this.authToken = token;
});

This is what I've been playing around with, and it works, but only if I hardcode the token (instead of using this.token )

getUsers(): Observable<User[]> {
  return this.http.get<User[]>(this.url + '/users', {
    headers: { 'Authorization': 'Bearer ' + this.authToken }
  })
    .pipe(
      tap(_ => console.log('users fetched')),
      catchError(this.handleError<User[]>('getUsers()'))
    );
}

I've tried wrapping the token fetch around the http call, but the IDE throws an error that I'm not returning anything

getUsers(): Observable<User[]> {
  this.authService.fetchToken().then(token => {
    return this.http.get<User[]>(this.url + '/users', {
      headers: { 'Authorization': 'Bearer ' + this.authToken }
    })
      .pipe(
        tap(_ => console.log('users fetched')),
        catchError(this.handleError<User[]>('getUsers()'))
      );
  });
}

This is how I'm calling it in my home.page.ts file

getUsers() {
  return this.apiService.getUsers().subscribe((data: any) => {
    this.users = data.data;
  });
}

Pulling my hair out at this point, as I've probably tried about 20 different ways to do this and each thing I try either throws an error or doesn't return anything.
This is what I was originally using in my home.page.ts file, but it didn't seem to work too well in an API service, which is why I'm trying observables

async getData(): Promise<any> {
  await this.authService.fetchToken().then(token => {
    if (token) {
      this.http.get(this.apiService.url + '/users', {
        headers: { 'Authorization': 'Bearer ' + token }
      }).subscribe(
        (result: any) => {
          this.users = result.data;
        }, error => {
          this.toastService.oops();
        });
    }
  });
}
ix0qys7i

ix0qys7i1#

您缺少return语句。而且我不确定您是否应该将observable和promises混合在一起-这只会使您的工作更加困难。(因此您最好将fetchToken也转换为返回observable。)

getUsers(): Observable<User[]> {
  return /**/ this.authService.fetchToken().then(token => {
    return this.http.get<User[]>(this.url + '/users', {
      headers: { 'Authorization': 'Bearer ' + token }
    })
      .pipe(
        tap(_ => console.log('users fetched')),
        catchError(this.handleError<User[]>('getUsers()'))
      ).toPromise(); /*Observable is not promise*/
  });
}

相关问题