Angularjs 在Angular 2中进行身份验证,处理观察值

Angularjs 在Angular 2中进行身份验证,处理观察值,angularjs,authentication,angular,angular2-routing,Angularjs,Authentication,Angular,Angular2 Routing,我刚开始一个Angular 2项目,正在尝试启动并运行身份验证。受此启发,我决定做以下工作: 创建一个自定义RouterOutlet类(扩展它),以便在调用url时处理身份验证逻辑 我成功地完成了这个自定义类,但仍然不确定如何检查用户是否经过身份验证。我的情况如下,我需要查询对外部API的get调用,对于我的开发过程如下: getAdmin() { let headers = new Headers({ 'Content-Type': 'application/json' });

我刚开始一个Angular 2项目,正在尝试启动并运行身份验证。受此启发,我决定做以下工作:

  • 创建一个自定义RouterOutlet类(扩展它),以便在调用url时处理身份验证逻辑
我成功地完成了这个自定义类,但仍然不确定如何检查用户是否经过身份验证。我的情况如下,我需要查询对外部API的get调用,对于我的开发过程如下:

getAdmin() {
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    return this.http.get('http://localhost:3000/admin/is_admin.json', options)
        .map(res => res)
        .catch(this.handleError)
}
此API调用返回true或false。我想知道使用这些信息的最佳选择是什么?例如,我是否应该在每次检查URL时调用以下函数

isAdmin() {
    this.getAdmin().subscribe(
        data => this.authenticationResult = data,
        error => console.log("Error: ", error),
        () => return JSON.parse(this.authenticationResult._data);
}

我不能让这个运行起来,因为在使用我给出的函数时,我的观察值是不确定的。

< P>我会考虑调用GETAdmin()作为应用程序的第一步,将结果存储在使用依赖注入的移动服务对象中。这样,在需要检查getAdmin结果的任何时候,都可以询问SessionService实例。 我希望这有帮助

问题在于,您的方法是异步的,因此您需要小心使用方法和时间

如果要在自定义的
RouterOutlet
activate
方法中使用,则需要利用可观察和反应式编程

我不知道您希望以何种方式检查管理员角色:

activate(instruction: ComponentInstruction) {
  return this.userService.getAdmin().flatMap((isAdmin) => {
    if (this.userService.isLoggIn()) {
      if (this._canActivate(instruction.urlPath, isAdmin) {
        return Observable.fromPromise(super.activate(instruction));
      } else {
        this.router.navigate(['Forbidden']);
        return Observable.throw('Forbidden');
      }
    } else {
      this.router.navigate(['Login']);
      return Observable.throw('Not authenticated');
    }
  }).toPromise();
}

_canActivate(url, admin) {
  return this.publicRoutes.indexOf(url) !== -1
    || this.userService.isLoggedIn();
}
为了优化请求,您可以延迟(并且只能一次)调用请求以检查用户是否为管理员:

isAdmin:boolean;

getAdmin() {
  if (this.isAdmin) {
    return Observable.of(this.isAdmin);
  } else {
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    return this.http.get('http://localhost:3000/admin/is_admin.json', options)
      .map(res => res)
      .catch(this.handleError);
   }
}
另一种方法是在验证用户时加载此提示。这样,
activate
方法的实现将更加简单:

activate(instruction: ComponentInstruction) {
  if (this.userService.isLoggIn()) {
    if (this.userService.isAdmin()) {
      return super.activate(instruction);
    } else if (this._canActivate(instruction.urlPath, isAdmin) {
      return super.activate(instruction);
    } else {
      this.router.navigate(['Forbidden']);
    }
  } else {
    this.router.navigate(['Login']);
  }
}

_canActivate(url, admin) {
  return this.publicRoutes.indexOf(url) !== -1
    || this.userService.isLoggedIn();
}