使用 angular 凭据成功登录后如何从登录导航到主页

时间:2021-02-22 10:09:22

标签: angular typescript angular6 angular2-routing

在我的 angular 应用程序中,我有具有用户凭据的 json 数据,这些数据在 angular 应用程序中被创建为 .json 文件

usercredentials.json



[
    {
        "name": "Admin",
        "permission": "all",
        "password": "Admin"
    },
    {
      "name": "MyName",
      "permission": "none",
      "password": "test"
    }
]

仅当凭据正确(即用户名:Admin 和密码:Admin)时,它才会导航到主页

auth.service.ts

export class AuthService {

  private httpOptions: any;
  public profile: any;
  public username: string;
  public password : any;
  public usr :any;

  constructor(private http: HttpClient, private router: Router) { }

  
  login(username: string, password: string): Observable<any> {
    
    return this.http.post('./app/usercredentials.json', { username, password })

  }
}

login.component.ts

constructor(private ds: AuthService, private http: HttpClient, private router: Router) { }

  public userinfo: any = [];
  public name:string;
  public password:any;
  public username :string;
  public user : any;
  
  ngOnInit(): void {
this.ds.login(this.username,this.password)
      .subscribe((userinfo) => {
        this.userinfo = userinfo;

        console.log('obj', this.userinfo);
        this.name = this.userinfo.name;
        this.password = this.userinfo.password;
        localStorage.setItem('user',this.name);
        localStorage.setItem('passwrd',this.password);
        if(localStorage.getItem('user')){
          this.router.navigate(['/home']);

        }

      },

        err => {
          console.log("Error", err)
        }
      );


  }

login.component.html

 <form>
        <input type="text" id="login" class="fadeIn second" name="uname" placeholder="Username" ><br>
        <input type="password" id="password" class="fadeIn third" name="pw" placeholder="Password" ><br><br>
        <input type="submit" class="fadeIn fourth" value="Submit">
      </form>

我的要求是... 验证成功后导航到主页并 登录失败的完整尝试显示错误消息。

1 个答案:

答案 0 :(得分:0)

您应该为您的路线使用路线守卫

请参考此链接Route Guard

示例,

在你的路线中

{
  path: '/home-page',
  component: HomePageComponent,
  canActivate: [AuthGuard],
}

并添加AuthGuard类,

export class AuthGuard implements CanActivate {
  canActivate(
    next: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
     const user = sessionStorage.getItem('user');

     if (user == null) {
       return of(this.router.createUrlTree(['login']));
     }

    return of(true);
  }
}