How to use canActivate () observed in angular 2 guards

I created an authentication protector for my angular2 rc5 application.

I also use redux store. In this store, I save user authentication status.

I read that a guard can return what is observed or promised ( https://angular.io/docs/ts/latest/guide/router.html#!#guards )

I can’t find a way for the guard to wait until the store / monitored is updated , and only after which it updates will return the guard, since the store’s default value will always be false.

First try:

@Injectable()
export class AuthGuard implements CanActivate {

  @select(['user', 'authenticated']) authenticated$: Observable<boolean>;

  constructor() {}

  canActivate(): Promise<boolean> {

    return new Promise((resolve, reject) => {

      // updated after a while ->
      this.authenticated$.subscribe((auth) => {

        // will only reach here after the first update of the store
        if (auth) { resolve(true); }

        // it will always reject because the default value
        // is always false and it takes time to update the store
        reject(false);

      });

    });

  }

}

Second attempt:

@Injectable()
export class AuthGuard implements CanActivate {

  @select(['user', 'authenticated']) authenticated$: Observable<boolean>;

  constructor() {}

  canActivate(): Promise<boolean> {

    return new Promise((resolve, reject) => {

      // tried to convert it for single read since canActivate is called every time. So I actually don't want to subscribe here. 
      let auth = this.authenticated$.toPromise(); 

      auth.then((authenticated) => {

        if (authenticated) { resolve(true); }

        reject(false);

      });

      auth.catch((err) => {
        console.log(err);
      });

  }

}
0
source share
3

, ; CompleteGet. CompleteGet() , , . , , , .

getCursenByDateTest(){
 this.cursenService
   .getCursenValueByDateTest("2016-7-30","2016-7-31")
   .subscribe(p => {
     this.cursens = p;
     console.log(p)
     console.log(this.cursens.length);
   },
   error => this.error = error,
   () => this.CompleteGet());
}

completeGet() {
   // the rest of your logic here - only executes on obtaining result.
}

, .do() , .

0

, , :

canActivate(): Observable<boolean> {
    return this.authenticated$.take(1);
}

: canActivate ( , , ), authenticated$ .next(), .complete()

: http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-take
.take(1) , ,

Edit2: , , - store.select() , .next

0

Subscription does not return Observable. However, you can use the map operator as follows:

this.authenticated$.map(
    authenticated => {
        if(authenticated) {
            return true;
        } 
    return false;
    }
 ).first() // or .take(1) to complete on the first event emit
0
source

Source: https://habr.com/ru/post/1656181/


All Articles