通过检查用户是否使用angular api登录来验证组件页面

问题描述 投票:0回答:1

如何验证包组件页面?在这个用户通过api服务文件登录,但即使没有登录并通过键入url导航到包页面。只有当用户登录时才应该进入包页面,否则它应该重定向到登录页面,甚至键入url。

login.component.ts

import { Component,ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { ApiService } from '../services/api.service';

@Component({
  templateUrl: './login.html'
})
export class LoginComponent {
  constructor(private router: Router,private ApiService:ApiService) {}
  public user:User = new User();

  login(user:any) {
    this.ApiService
        .loginAdmin(user)
        .subscribe(
         user  => {
            this.router.navigate(['/category']);
       },     
        error => {
          console.log(error);
      });
   }
}

export class User {
  public email:string;
  public password: string;
  public token: string;
}

package.component.ts

import { Component} from '@angular/core';
import { Router } from '@angular/router';
import { ApiService } from '../services/api.service';

@Component({
  templateUrl: './package.html'
})
export class PackageComponent {
  constructor(private router: Router,private ApiService:ApiService){}
  ngOnInit(){
  this.ApiService
    .package()
    .subscribe(
      user => {
         this.router.navigate(['/package']);
      }),
      error => {
        this.router.navigate(['/login']);
      }
  }
}

api.service.ts

export class ApiService {
constructor (private http: Http) { }

public Auth:any;

loginAdmin(user: Object) {
  return this.http
    .post(urlBase + 'users/adminLogin',user)
    .map(response => {
      var auth = response.json();
      localStorage.clear();
      localStorage.setItem('authToken', JSON.stringify(auth.data[0].token));
      localStorage.setItem('userEmail', JSON.stringify(auth.data[0].email));
      localStorage.setItem('userId', JSON.stringify(auth.data[0]._id));
      this.login=true;
      return auth;
    })
    .catch(this.handleError);
}

private extractData(res: Response) {
  let body = res.json();
  return body || { };
}

private handleError (error: Response | any) {
  let errMsg: string;
  if (error instanceof Response) {
    const body = error.json() || '';
    const err = body.message || JSON.stringify(body);
    errMsg = `${err}`;
  } else {
    errMsg = error.message ? error.message : error.toString();
  }
  return Observable.throw(errMsg);
  }
  
  package(){
    
  }
}
angular api typescript
1个回答
0
投票

您的示例中缺少ApiService.package实现。但无论如何,这不是进行此类安全检查的正确方法。

你应该学会使用路线保护(official guide here

主要优点是您的安全逻辑与组件分离,如果未满足要求,您的组件甚至不会被实例化。

© www.soinside.com 2019 - 2024. All rights reserved.