首页 > 解决方案 > Angular:在不同条件下登录后重定向到不同页面

问题描述

我有一个简单的登录,您可以在其中输入电子邮件和密码,如果它在数据库中可用,则用户可以登录。但登录后的用户必须重定向到特定页面。

例如:如果用户登录类型是“供应商”,则用户必须重定向到特定页面,否则用户必须重定向到另一个页面。

这是服务方法

  login(email, password): any {
    const headers = new HttpHeaders({
      'Content-Type': 'application/json'
    });
    return this.http
      .post(this.uri + '/login', { email, password }, {headers})
      .pipe(catchError(this.errorHandler));

  }

如果用户没有输入“供应商”,我想重定向到仪表板

     this.router.navigate(['dashboard']);

如果用户是供应商,我想重定向到“供应商”

    this.router.navigate(['supplier']);

来自后端的用户对象如下

error: false
result:
email: "din@gmail.com"
phone_no: "00000008"
type: "supplier"
user_id: 1

对于 ref,这是 ts 文件方法

loginToSystem(): any {
    const email = this.formData().email;
    const password = this.formData().password;

    this.backendService.login(email, password)
      .subscribe(data => {
        this.loginData = data;
        console.log(data);
        // console.log('helo');
        console.log(data.result.type);
      });
    console.log(email, password);
  }

应用程序路由

const routes: Routes = [
  { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
  {path: 'login', component: LoginComponent},
  {path: 'dashboard', component: DashboardComponent},
  {path: 'supplier', component: SupplierComponent}
];

感谢您对此事的任何见解!谢谢!

标签: angular

解决方案


一个简单的 if() 不应该解决您的问题吗?

loginToSystem(): any {
    const email = this.formData().email;
    const password = this.formData().password;

    this.backendService.login(email, password)
      .subscribe(data => {
        this.loginData = data;
        if(data.result.type === 'supplier') {
          this.router.navigate(['supplier']);
        } else {
          this.router.navigate(['dashboard']
        }
      });
    console.log(email, password);
  }

如果您只有 2 个 level_types,这将是一个很好的解决方案


推荐阅读