在 Observable 中调用 Promise

Calling a Promise within a Observable

我想要完成的是能够从我的 getEmployees() 函数异步调用我的 getToken() promise,但不让它异步我的 getEmployees() 函数。

拜托,任何想法,非常感谢你。

employee.service

async getToken(): Promise < string > {
  return await this._auth._token();
}

getEmployees(): Observable < EmpleadoTarjeta[] > {

  const promiseSource = from(new Promise(async (resolve) => {
    await this.getToken().then(tokenUser => resolve(tokenUser));
  }));
  let token: any;
  promiseSource.subscribe(tokenPromise => token = tokenPromise);
  const httpHeaders: HttpHeaders = new HttpHeaders({
    tokenJPA: token,
  });

  console.log(token);
  return this._httpClient
    .get<EmpleadoTarjeta[]>('API', { headers: httpHeaders }
    )
    .pipe(
      map(response => response.map(item => new EmpleadoTarjeta(item))),
      tap((empleados) => {
        this._empleados.next(empleados);
      })
    );
}

_auth.service

async _token(): Promise<string> {
    const auth = getAuth();
    return auth.currentUser.getIdTokenResult(true).then(async token => token.token);
}

更新

getEmpleados(): Observable<EmpleadoTarjeta[]> {
 // const token: any = from(this.getToken()).toPromise().then(tokenUser  
=> tokenUser);
const promiseSource: any = from(this.getToken());
const httpHeaders: HttpHeaders = new HttpHeaders({
  tokenJPA: promiseSource.subscribe((tokenPromise: any) => {
    console.log(tokenPromise);
    return tokenPromise;
  }),
});

return this._httpClient
  .get<EmpleadoTarjeta[]>('http://localhost:5001/journeypadel/us-central1/fxManager_Empleados-empleadosRegistrados', { headers: httpHeaders }
  )
  .pipe(
    map(response => response.map(item => new EmpleadoTarjeta(item))),
    tap((empleados) => {
      this._empleados.next(empleados);
    })
  );
}

我是这样弄的,没用

您可以将其用作:

const promiseSource = from(this.getToken());

更新

getEmpleados(): Observable<EmpleadoTarjeta[]> {
  return from(this.getToken())
    .pipe(
      map((tokenUser) => new HttpHeaders({
        tokenJPA: tokenUser
      })),
      switchMap((httpHeaders) => this._httpClient
        .get<EmpleadoTarjeta[]>(
          'http://localhost:5001/journeypadel/us-central1/fxManager_Empleados-empleadosRegistrados',
          { headers: httpHeaders }
        )
        .pipe(
          map(response => response.map(item => new EmpleadoTarjeta(item))),
          tap((empleados) => {
            this._empleados.next(empleados);
          })
        ))
    );
}