Angular 2 Router.navigate in the service. Good practice?

I am creating an application in which there are many user roles. So when I log in and I return the user role in the response, and I need to move accordingly. I made the url-redirect.service.ts service and the one that created such a function.

redirect(user_role){ 

switch (user_role){
case 1: this.router.navigate[route1];
         break;
case 2: this.router.navigate[route2];
         break;

}

Like this.

But the point is login.component.ts after I delegate this thing for service. I have code to execute as follows:

this.urlService.redirect(res.data[0].user_roles);

setCookies();

setLanguage();

and so on;

Now it works great. But I just feel that this is wrong, because after that there is some code, and the route changes between them. I'm not sure what the pros and cons are. Can someone tell me if this is a good practice?

+4
1

. :

login(credentials: any): Observable<any> {
  return this.http.post(this.endpoint + '/login', credentials)
    .map(this.extractData)
    .do((user) => {
      this.user = user;
      console.warn('on successful login => navigate to redirectUrl');
      this.router.navigate([this.getRedirectUrl()]);
    })
    .catch((err) => {
      this.user = null;
      return this.handleError(err);
    });
}

, .do()

- ( ), , Observable ( ).

.do() , URL- .

, , router.navigate . , , , .

0

Source: https://habr.com/ru/post/1669089/


All Articles