在 Observable 中调用 Promise
2021-10-21
184
我想要实现的目标是能够从 getEmployees() 函数异步调用 getToken() 承诺,但不使 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);
})
);
}
我按照这种方式做了,但没有成功
1个回答
您可以将其用作:
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);
})
))
);
}
Ruslan Lekhman
2021-10-21