angular2:如何从ActivatedRoute获取组件实例?

时间:2018-01-03 12:22:29

标签: angular angular2-routing

我想从CanActivate guard方法调用当前活动组件的方法。 我试过这种方式,但检索到的 currentComponent 只是一个组件函数,而不是一个实例:

@Injectable()
export class ReservationGuard implements CanActivate {

  constructor(
    private router: Router){

  }

  canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

    const currentComponent = this.router.routerState.root.firstChild.firstChild.firstChild.component;

    // I'd like to call component's instance method which returns Observable<boolean>
    // return currentComponent.submit()

    return true;

  }
}

CanDeactivate后卫提供了一个组件实例,但我需要CanActivate后卫。

我已经使用EventEmitter进行了一些服务,以使其工作,但它看起来像一个糟糕的设计气味与不必要的'异步性'。

CanActivate后卫回归:

return Observable.create( newObservable => {

    this.reservationService.submitCurrentForm().subscribe(lastValidStep => 
      newObservable.next(lastValidStep + 1 >= navigatingStep)
    );

  });

ReservationService:

submitCurrentForm(): Observable<number> {
    this.submitEndEmitter = new ReplaySubject(1);
    this.submitCurrentFormEmitter.next();
    return this.submitEndEmitter;
  }

组件:

  this.reservationService.getSubmitCurrentFormEmitter().subscribe( () => 
      this.submit()
  );

0 个答案:

没有答案