如果用户使用NavigationByUrl更改了密码,则Angular 6重定向到应用程序的启动组件

时间:2018-10-25 07:47:05

标签: angular angular6 router

我目前位于我的angular 6应用程序的以下网址:

http://localhost:4200/dashboard/admin/users

如果管理员更改了他的凭据,我需要再次将他重定向到登录组件。

this.auth.updateCredentials(credentials).subscribe(
  (data) => {
    if (data == "success") {
      this.showError = false;
      if (credentials['user_id'] == this.loggedUser) {
        //Redirect
        localStorage.setItem('jwt', '')
        localStorage.setItem('user_id', '')
        localStorage.setItem('user_role', '')
        this.router.navigateByUrl('login');
      } else {
        this.dialogRef.close();
      }
    }
    if (data == "error") {
      this.showError = true;
    }

  },
  (error) => {
    this.showError = true;
    console.log(error);
  }
);

我尝试了this.router.navigateByUrl('login');this.router.navigateByUrl('/login');

但没有错误,也没有重定向

3 个答案:

答案 0 :(得分:1)

尝试一下:

constructor(..., private router: Router, ...) {}
...
this.router.navigate(['/login']);
...

答案 1 :(得分:1)

import从'@ angular / router'导入{Router}; 并在构造函数专用路由器中:路由器

如果您将服务请求作为json传递,则代码不像

this.auth.updateCredentials(credentials).subscribe(
  (data) => {
    if (data) {
      this.showError = false;
      if (credentials['user_id'] == this.loggedUser) {
        //Redirect
        localStorage.setItem('jwt', '')
        localStorage.setItem('user_id', '')
        localStorage.setItem('user_role', '')
         this.router.navigate(['your link']).then(() => {
                  your toaster
                });
      } else {
        this.dialogRef.close();
      }
    }
    if (data == "error") {
      this.showError = true;
    }

  },
  (error) => {
    this.showError = true;
    console.log(error);
  }
);

如果您没有提前将数据解析为json,则必须执行

this.auth.updateCredentials(credentials).subscribe(
  (data) => {
    if (data['status'] == 200) {
      this.showError = false;
      if (credentials['user_id'] == this.loggedUser) {
        //Redirect
        localStorage.setItem('jwt', '')
        localStorage.setItem('user_id', '')
        localStorage.setItem('user_role', '')
        this.router.navigate(['your link']).then(() => {
                    your toaster
      } else {
        this.dialogRef.close();
      }
    }
    if (data == "error") {
      this.showError = true;
    }

  },
  (error) => {
    this.showError = true;
    console.log(error);
  }
);

答案 2 :(得分:1)

如果您正在使用

import { Router } from '@angular/router'

确保您的构造器中的身份为

constructor(private _router: Router) {}

并使用正斜杠指定路线

 this._router.navigateByUrl("/login")

也许这就是您所缺少的。希望对您有所帮助。