In my service, I am doing a post-service call to get some data but before calling the POST API I am doing a GET call to get auth token which I will use in the post-call. Now I have used async-await to wait until GET API returns the token and then does POST but it is not happening that way. Till the time token comes, the post-call is already completed. I want to call them in a synchronous manner that is first GET the token and then does the POST
My component abc.ts
async ngOnInit(): Promise<void> {
(await this.abcservice.fetchDetails(this.id, this.name))
.subscribe(
(data: any) => {
this.result = data.value;
},
(error) => {
this.ErrorHandler(error);
}
);
}
In my service abc-service.ts
async getToken() {
this.tokenService.getToken().subscribe(resp => {
if (resp.headers) {
this.headerDict = {
'x-token': resp.headers.get('x-token')
};
this.requestOptions = {
headers: new HttpHeaders(this.headerDict)
};
}
});
}
public async fetchDetails(payload: any) {
await this.getToken();
return this.http.post<any>(this.url,payload, this.requestOptions);
}
In token-service.ts
getToken() {
return this.httpClient.get<any>(url, { observe: 'response' });
}
Can anyone please point out what is wrong I am doing?