0
I’m having some doubts about the life cycle in Angular 7, when making a request for a certain API needed before I have picked up your token that also comes through the API, in another get.
The doubt is in the sequence of things, I come from programming for SCADA systems, where everything is kind of archaic and I need to develop a touch search box in angular, so the lack of practice.
I am calling the token (which returns) after ngOnInit, but as I request the API that uses the code right away, it returns invalid due to missing token, so I believe I am lost in the lifecycle of the angular.
Requesting the token (a service.ts)
getToken(): Observable<TokenHistorian[]> {
return this.http.get<TokenHistorian[]>(ApiToken)
.pipe(
catchError(this.handleError('getToken', []))
);
}
The model
export class TokenHistorian{
access_token: string;
}
The Component.ts
export class PesquisahistorianComponent implements OnInit {
valorToken: TokenHistorian[];
tokenFinal: string;
constructor(private _api: ApiService) { }
ngOnInit() {
this.geraToken();
console.log('http://localhost/api_cco/ifix/volume_res.php?token='+this.tokenFinal);
}
public geraToken = async () => {
await this._api.getToken()
.subscribe(returntoken => {
this.valorToken = returntoken;
this.tokenFinal = this.valorToken['0'].access_token;
console.log(this.tokenFinal);
}, err => {
console.log(err);
});
}
}
The console.log below geraToken() returns as Undefined.
Resolved issue!
After some rest we always think better...
I did some research and now I can wait for the httpclient to return before proceeding with the rest of the code (still implementing a loading)
async ngOnInit() {
await this.geraToken();
console.log('http://localhost/api_cco/ifix/volume_res.php?token='+this.tokenFinal);}
And the function becomes asynchronous (I don’t know if effectively).
public geraToken = async () => {
await this._api.getToken().then(data =>{
this.teste =data;
this.tokenFinal = data['0'].access_token;
console.log(this.tokenFinal);
});}
The call from the API
async getToken(): Promise<TokenHistorian[]> {
return await this.http.get<TokenHistorian[]>(ApiToken).toPromise().then(); }
Hello Andre. See if it works by placing the console inside a
then()
on the call ofgeraToken()
. Since it is an asynchronous function, Angular may be running the console before the Token request ends. it would look something likethis.geraToken().Then(() => console.log(url + this.tokenFinal));
– Lucas Ayrosa
I got it using async Lucas, thanks for the tips.
– Andre Astafieff