S
S
sdgroup142018-06-28 14:50:32
Angular
sdgroup14, 2018-06-28 14:50:32

There is an Authentication service. How to make it general for the whole project?

Hi all! I am writing a project in Angular 2+. I am currently using the latest version. I used to do light projects and now I understand what I did with a crutch. Essence of a question... Is for example a "news" portal it has header and content blocks. Without Authentication, let's say the author cannot edit his news and the login button is lit in the header.
when I logged in, a pencil appeared and its icon in the header ... Is it really necessary to add this service in each component out of 100 in the constructor that checks my JWT token and then only in onInit check what to show it .... also a question about roles ... Really it’s impossible to somehow make it 1 time for the entire project so that each component understands that it is necessary to initially check the token and then issue it according to the result? Well, I understand a similar scheme for localization?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Stroykin, 2018-06-28
@sdgroup14

You will have an AuthGuard that will control access to the sections and you can write a directive that will control the display of the UI on the page. Let the directive be called, for example, "hasAuth" and have the following content:

@Directive({ selector: '[hasAuth]' })
export class HasAuthDirective implements OnInit {
  constructor(private _viewContainer: ViewContainerRef, private _template: TemplateRef<any>) { }

  ngOnInit(): void {
    this._checkAuth(/*ваше определение аутентификации типа boolean*/);
  }

  private _checkAuth(isAuth: boolean): void {
    if (isAuth) {
      this._viewContainer.createEmbeddedView(this._template);
    } else {
      this._viewContainer.clear();
    }
  }
}

And in the template, where you need to show/hide a button or another UI depending on whether the user is authenticated, just add the directive we created: I sketched a mini example - link Regarding "localization". Also, there is nothing complicated. I recommend using ngx-translate . In principle, there is all the necessary information on "how to use it."

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question