简体   繁体   中英

Angular2 CanActivate global function declaration

I like to implement @CanActivate(() => checkpermission()) in all my component. Here i am facing one issue.

checkpermission is not a function

how to declare function globally. For global function, now i am using services. Is it possible to call service function inside

@CanActivate(() => checkpermission())

You can make it global this way,

NOTE : This ans may contain some extra stuffs (which probably you don't require). So you may concentrate on the things you require and ignore other unrequired stuffs. I have put this ans by considering more global scenario(eg - what if you want to inject some external service into checkpermission function)

checkpermission.ts

import {Injector} from 'angular2/core';
import {appInjector} from './app-injector';
import {externalService} from './externalService'; <---------------------- //some external service
import {Router, ComponentInstruction} from 'angular2/router';

export const checkpermission= (next: ComponentInstruction, previous: ComponentInstruction) => {

    let injector: Injector = appInjector(); // get the stored reference to the injector
    let externalService: externalService= injector.get(externalService);
    let router: Router = injector.get(Router);

    // return a boolean or a promise that resolves a boolean

    return new Promise((resolve) => {

                       //here you can play with externalService

                        if(something is true)
                           resolve(true);
                        else 
                           resolve(false);

    });
};


somecomponent.ts

In somecomponent you can use checkpermission.ts like this,

 import {checkpermission} from './checkpermission'; @CanActivate((next: ComponentInstruction, previous: ComponentInstruction) => { return checkpermission(next, previous); }) 


app-injector.ts

 import {Injector} from 'angular2/core'; let appInjectorRef: Injector; export const appInjector = (injector?: Injector):Injector => { if (injector) { appInjectorRef = injector; } return appInjectorRef; }; 

I hope it will fulfill you requirement.

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