Angular 2 - Custom annotations

Is possible to create a custom annotation in Angular 2?. For example an annotation @LoginRequired, where after all it checks if user logged, if it is, continue with the component. In case the user is not logged navigate to a page error.

Upvotes: 4

Views: 7174

Answers (1)

Marcus Krahl
Marcus Krahl

Reputation: 684

The decorators or as you call them annotations are not part of Angular 2 itself, but of the TypeScript language.

The Typescript documentation gives an introduction on how to write these decorators to decorate classes, methods and so on.

You can just define a decorator as:

export function f() {
    //do something
}

And later use it as:

import { f } from "./your-decorator-module";

@f()
export class MyClass { }

However the functionality you describe (go to an error page if the user is not logged in) is better implemented by defining a router guard for the component. You can follow the Angular 2 Tutorial on Routing to accomplish this result

Upvotes: 11

Related Questions