我喜欢在我的所有组件中实现@CanActivate(() => checkpermission())
。在这里,我面临一个问题。
checkpermission is not a function
如何全局声明函数。对于全球功能,现在我正在使用服务。是否可以在
中调用服务功能@CanActivate(() => checkpermission())
答案 0 :(得分:1)
你可以通过这种方式使其全球化,
注意:此ans可能包含一些额外的内容(可能您不需要)。所以你可以专注于你需要的东西,而忽略其他不需要的东西。我已经考虑了更多的全局场景(例如 - 如果你想将一些外部服务注入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);
});
};
<小时/> 的 somecomponent.ts 强>
在某些组件中,您可以像这样使用 checkpermission.ts ,
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;
};
我希望它能满足你的要求。