What I am trying to accomplish is to be able to call my getToken() promise asynchronously from my getEmployees() function but without making it asynchronous my getEmployees() function.
Please, any idea and thank you very much in advance.
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);
}
UPDATE
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);
})
);
}
I did it this way and it did not work
CodePudding user response:
You could just use it as:
const promiseSource = from(this.getToken());
UPDATE
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);
})
))
);
}