简体   繁体   English

Angular 2 CanActivate作为承诺,它从另一个组件解析

[英]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. 我试图解决canActivate钩从另一个组件和注入的服务,但卡住了。 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 (返回真实的表单守卫将重新路由该路由。成功订阅worker发射器将触发火灾。)代码为: worker.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 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 some.component.ts

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

What i'm doing wrong? 我做错了什么? I was tried with Promises too. 我也曾尝试过Promises。

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 : 如果我们将其与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 : 回到我们的Observable,而不是做:

  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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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