Angular 2: Inject a dependency into @CanActivate?

后端 未结 5 1191
心在旅途
心在旅途 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:15

    Most solutions here will present problems with loading sub-dependencies from elsewhere in the hierarchy, because they create a new injector. Also, this results in additional (non-shared) services being instanced. I recommend following the pattern provided by Brandon in https://github.com/angular/angular/issues/4112

    He references this Plunk: http://plnkr.co/edit/SF8gsYN1SvmUbkosHjqQ?p=preview

    Its main idea is a singleton injector, which he saves when the app initializes. This provides access to the root dependencies you already have configured, and further allows your services to be shared as a singleton as they were probably intended:

    import {Injector} from 'angular2/angular2';
    let appInjectorRef: Injector;
    
    export const appInjector = (injector?: Injector):Injector => {
        if (injector) {
          appInjectorRef = injector;
        }
    
        return appInjectorRef;
    };
    
    bootstrap([ServiceYouNeed]).then((appRef) => {
        // store a reference to the injector
        appInjector(appRef.injector);
    });
    

提交回复
热议问题