Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - Custom annotations

Tags:

angular

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.

like image 334
Matías González Avatar asked Dec 24 '22 01:12

Matías González


1 Answers

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

like image 70
Marcus Krahl Avatar answered Dec 28 '22 10:12

Marcus Krahl