2016-05-14 56 views
0

我有一個裝飾有@CanActivate的組件。Angular 2 routing-deprecated:如何檢測CanActivate?

@Component({ 
    // ... 
}) 
@CanActivate(() => false) 
export class UserManagementComponent { 
    // ... 
} 

在我的導航菜單中,我想禁用或隱藏導航到此路線的鏈接。我會如何去做這件事? PS:我仍然使用不推薦的路由機制,而不是rc1版本。

+0

我想返回值並不總是靜態'FALSE'而這只是這個例子?通常它是從一些條件計算出來的。 –

+0

事實上,只是爲了保持簡單的例子。 – Aetherix

回答

2

如果您將@CanActivate(() => ...)返回值的計算移到服務中,那麼您可以從整個應用程序訪問它。您可以創建一個指令並將其添加到注入服務的routerLink,並在路線的條件返回false時禁用routerLink

請參閱http://almerosteyn.com/2016/04/linkup-custom-control-to-ngcontrol-ngmodel關於如何在@CanActivate中使用DI。

Angular 2, disable routerLinkAngular2, what is the correct way to disable an anchor element?如何禁用routerLink

0

我相信有一個注入的服務是很長的路要走,因爲如果你在任何時候需要路由到其他附加組件的組件,它會是多少更容易,而且您不必複製反射代碼。

這就是說,我很好奇如何做反思的確。所以它似乎應該被添加到ES7規範。現在,「反射元數據」包pollyfills爲它,這也是Angular2內部使用。雖然'Reflect'已經是TypeScript庫的一部分,但我沒有找到任何元數據反射,似乎它只支持對象反射。

//This is a bit hacky, but it might help. 
... 
export class Test { 
    ... 
    logType(target : any, key : string) { 
     //stop TypeScript from mapping this to TypeScript Reflect. 
     var Reflect = Reflect || {}; 

     //You still get an error if you havn't added the Reflect.js script in the page 
     var t = Reflect.getMetadata("design:type", target, key); 

     console.log('key:' + key + ' type: ' + t.name); 
    } 
    ... 
} 

來源:

http://blog.wolksoftware.com/decorators-metadata-reflection-in-typescript-from-novice-to-expert-part-4

https://www.npmjs.com/package/reflect-metadata