Angular 2: Inject a dependency into @CanActivate?

后端 未结 5 1203
心在旅途
心在旅途 2021-01-02 06:55

In Angular 2, you can specify a @CanActivate annotation for a component where you can determine if the component should be activated or not. The reason it\'s no

5条回答
  •  无人及你
    2021-01-02 07:00

    You have to inject it using injector. Just a quick copy paste from a project I'm doing:

    @CanActivate((next: ComponentInstruction, prev: ComponentInstruction) => {
    
      console.info('CanActivate hook! - can return boolean or Promise');
    
      var injector = Injector.resolveAndCreate([HTTP_PROVIDERS, YourService]);
      var yourService = injector.get(YourService);
      // do something with yourService
      return new Promise(function(resolve, reject) {
          resolve(true);
      });
    
    })
    

    HTTP_PROVIDERS you have to pass along if your service is for example injecting the HTTP service in the constructor.

    I use it to put an observable on the params of the next object. And the next object is your next "Component/state":

    @CanActivate((next: ComponentInstruction, prev: ComponentInstruction) => {
    
      console.info('properties component CanActivate hook! - can return boolean or Promise');
      var injector = Injector.resolveAndCreate([HTTP_PROVIDERS, PropertiesService]);
      var propertiesService = injector.get(PropertiesService);
      return new Promise(function(resolve, reject) {
          next.params['properties'] = propertiesService.getProperties();
          resolve(true);
      });
    
    })
    

    The PropertiesService calls a backend and returns an Observable that represents the data with properties

提交回复
热议问题