Consider the following function
Go(publicRoute: boolean, token: string) {
let rtrn = {} as aaResult;
if (publicRoute) {
rtrn.Authenticated = true;
}
else {
if (token != "" || this.userService.Get() != null) {
if (this.userService.Get() != null) {
rtrn.Authenticated = true;
}
else {
this._authorize(token).subscribe(res => {
console.log("internal subscribe");
console.log(res);
this.userService.Set(new User(res));
if (this.userService.Get() != null) {
rtrn.Authenticated = true;
rtrn.User = this.userService.Get()
}
else
this._authenticate();
}
,
error => {
this._authenticate();
}
)
}
}
else {
this._authenticate();
}
}
return (Observable.of(rtrn));
}
If the first if is true the return data is correct. If the if is false the return data is {} because the function doesn't wait for the results of this._authorize. How can I make the function wait for the result of internal observable?
This is how the whole thing gets called, just in case:
this.AA.Go(this.publicRoute, this.internalToken).subscribe(res => { console.log(res) })
EDIT
Adding code for the authorize function turned into observable
private _authorize(token: string, options?: any): Promise<User> {
return this.http.get<User>(this.config.aa.autherizationUrl + "?token=" + token, {
headers: this.Utils.SetRequestAppOptions(options === undefined ? {} : options),
}).toPromise();
}
UserService.Get()returning anObservable? - Chau Tran_authenticate()? - Chau Tranreturnstatement in thesubscribeblock. Then place couple morereturnstatements in the function or usetoPromiseso you can async/await it without subscribing ;) - Chau Tran