Angular 2 中的身份验证,处理可观察对象

Authentication in Angular 2, handling the observables

我刚开始一个 Angular 2 项目,正在尝试进行身份验证和 运行。受到 this tutorial 的启发,我决定执行以下操作:

我在这个自定义中成功了 class,但我仍然不确定如何检查用户是否已通过身份验证。我的情况如下,我需要查询一个外部的get调用API,我的开发过程如下:

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调用returns判断对错。我想知道使用这些信息的最佳选择是什么?例如,我是否应该在每次检查 URL 时调用以下函数?:

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

我做不到,运行 因为在使用我给出的示例函数时,我的 observable 是未定义的。

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

"problem"是你的方法是异步的,所以你在使用的时候和方式上要小心。

如果您想在自定义 RouterOutletactivate 方法中使用,您需要利用可观察对象和反应式编程。

我不知道你想要检查管理员角色的确切方式:

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();
}