Home » Javascript » Angular 5 nested returns

Angular 5 nested returns

Posted by: admin June 30, 2018 Leave a comment

Questions:

i am trying to create a function that should return a boolean after calling my API

so i created the following function:

verify() {
    console.log('lol');
    let user = JSON.parse(localStorage.getItem('currentUser')) as User;
    return this.http.get(environment.apiUrl + 'Users/' + user.id,
        {params: ApiHelperService.prototype.createParams([], true)}).subscribe(
        result => {
            return true;
        },
        error => {
            return false;
        }
    );

}

And then i called it:

if (this._userService.verify()) {
    return true;
}
else {
    this._router.navigate(['/login'], {queryParams: {returnUrl: state.url}});
    return false;
}

However, sadly the function returns before the response from the server.

So my question is how can I create these nested return statements to make sure it returns the correct value?

Answers: