0

I am trying to validate a user token by the means of a back-end API. I am brand new to Angular2 in general. My question is, if I want isValidToken to return a boolean value of whether or not the token provided was valid, how can I wait for the HTTP call to complete prior to return in result from isValidToken()?

isValidToken(token: string): boolean {
    var isValidToken: boolean = false;
    this.getIsValidToken(token).subscribe(
        data => {
            isValidToken = data.isValidToken;
            return isValidToken;
        },
        error => {
            return false;
        }
    );
}

getIsValidToken(token: string) {
    return this.http.get(this.validateTokenUrl + '?tokenString=' + token)
        .map(res => res.json());
}

2 Answers 2

1

isValidToken needs to return Observable<boolean> or Promise<boolean>. It can't return the value synchronously because it relies on an asynchronous method for it's result.

It's turtles all the way down.

Sign up to request clarification or add additional context in comments.

1 Comment

Yea, I've been reading that all over. Can you give an example though on how I can use the returned value in another method?
0
isValidToken(token: string): boolean {
    return this.getIsValidToken(token);
}

getIsValidToken(token: string) {
    return this.http.get(this.validateTokenUrl + '?tokenString=' + token)
        .map(res => res.json());
}

then you can use it like

someMethod() {
  this.isValidToken.subscribe(token => {
    if(token) {
      this.success = true;
      // or some other code that should be executed when `token` is `true`
    } else {
      this.success = false;
      // or some other code that should be executed when `token` is `false`
    }
  },
  error => {
      this.success = false;
      // or some other code that should be executed when `token` is `false`
  });
}

You can't go to sync execution from an async call. All you can do is return the observable (or promise) for the caller to be able to subscribe and register a callback to be called when data events are emitted or errors occur.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.