简体   繁体   中英

Angular 2 routing-deprecated: How to detect CanActivate?

I have a component that is decorated with @CanActivate .

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

In my navigation menu I'd like to disable or hide the link that navigates to this route. How would I go about doing this?

<a [routerLink]="['UserManagement']">User management</a>

PS: I'm still on the deprecated routing mechanism, not the rc1 version.

If you move the calculation of the @CanActivate(() => ...) return value to a service, then you can access it from your whole application. You can create a directive and add it to the routerLink that injects the service and disables the routerLink when the condition for the route returns false .

See http://almerosteyn.com/2016/04/linkup-custom-control-to-ngcontrol-ngmodel for how to use DI in @CanActivate .

See Angular 2, disable routerLink and Angular2, what is the correct way to disable an anchor element? for how to disable a routerLink

I believe having an injected service is a way to go, because if you ever need to route to your component from other additional components, it'll be much easier and you don't have to duplicate the reflection code.

That being said, I was curious on how to do the reflection indeed. So it appears that's supposed to be added to ES7 specification. For now, 'reflection-metadata' package pollyfills for it and that's what Angular2 uses internally too. Although 'Reflect' is already part of TypeScript library, I didn't find any meta-data reflection and seems it only support object reflections.

//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);
    }
    ...
}

Sources:

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

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

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