M
M
Maxim Tarabrin2017-07-12 09:45:18
JavaScript
Maxim Tarabrin, 2017-07-12 09:45:18

How to process responses from server using Observable?

Can you please explain how to process responses from the server using the observable object?
I have routing configured and there is a defender who checks the token for validity. This is some kind of sandbox, I understand what's what in angular'e. If we allow, I will drive into the token not valid or even 0 for example. How to work in this case?
AuthenticationGuard(Checking the token for validity)

canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
      if(localStorage.getItem('Token')){
        let token = localStorage.getItem('Token');
        this.authService.verifyToken(token)
                        .subscribe(res => {
                          if(res['token'] == token){
                            this.router.navigate(['/login']);
                          }
                        });
        return true
      } else {
        this.router.navigate(["/login"]);
      }
  }

AuthService
backendUrl = "http://127.0.0.1:8000/";
  constructor(private http: Http,
              private router: Router) { }

  verifyToken(token: string): Observable<{}>{
    let urlVerify = 'api-token-verify'
    let headers = new Headers({'Content-Type':'application/json'});
    let options = new RequestOptions({headers: headers});
    return this.http.post(this.backendUrl+'api-token-verify/', {token}, options)
      .map((response: Response) => response.json())
      .catch(this.handleError);
  }

  handleError(error: any){
    return Observable.throw(error.message || error.json());
  }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nicholas, 2017-07-12
@padr1no

The guard in this case should return an Observable, or a Promise, and the result should be true/false depending on whether the check succeeded or not.
Here is an example: https://stackoverflow.com/questions/38425461/angul...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question