[英]Angular2 CanActivate global function declaration
I like to implement @CanActivate(() => checkpermission())
in all my component. 我喜欢在所有组件中实现
@CanActivate(() => checkpermission())
。 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). 注意:此ans可能包含一些其他内容(可能您不需要)。 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函数中,该怎么办)
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);
});
};
In somecomponent you can use checkpermission.ts like this, 在某些组件中,您可以像这样使用checkpermission.ts ,
import {checkpermission} from './checkpermission'; @CanActivate((next: ComponentInstruction, previous: ComponentInstruction) => { return checkpermission(next, previous); })
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. 我希望它能满足您的要求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.