简体   繁体   中英

Angular 2 CanActivate as promise, that resolves from another component

I am trying to resolve canActivate hook from another component and injected service, but something stuck. Guard and workers service are provided and working fine alone. (Returning true form guard resloves the route. Subscribing on workers emitters fires successful.) The code is: workers.service.ts

@Injectable()
export class WorkersService {
public mainCmpState: EventEmitter<any>;
constructor() {
   this.mainCmpState = new EventEmitter();
}
toggleMainCmpState(bool) {
    console.log('TOGGLE MAIN CMP' , bool);
    this.mainCmpState.emit(bool);
}

guard.service.ts

@Injectable()
export class GuardService implements CanActivate {
   constructor(public workers: WorkersService) {}

   canActivate() {
        console.log('CAN ACTIVATE IS CALLED');
        return Observable.create(observer => {
         this.workers.mainCmpState.subscribe((data) => {
                console.log('CAN ACTIVATE SUB', data);

                observer.next(true);
                observer.complete();
        });
    });
}

some.component.ts

//on some test button click
this.workers.toggleMainCmpState(true);

What i'm doing wrong? I was tried with Promises too.

What I was trying to explain in previous comments is that wrapping the subscription of an observable inside a newly created observable is not necessary.

If we were comparing that to Promise :

What you're doing here is something like that :

  canActivate() {
    return new Promise((resolve, reject) => {
      this.somePromiseYouAlreadyHave.then(() => {
        resolve(true)
      })
    })
  }

What you should be doing :

  canActivate() {
    return this.somePromiseYouAlreadyHave;
    // assuming this promise will be resolve with value true
  }

Going back to our Observable, instead of doing :

  canActivate() {
    console.log('CAN ACTIVATE IS CALLED');
    return Observable.create((observer: Subject<boolean>) => {
      this.workers.mainCmpState.subscribe(res => {
        observer.next(true);
      })
    });
  }

you should do :

return canActivate() {
  return this.workers.mainCmpState;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM