Angular 2 中的身份验证,处理可观察对象 [英] Authentication in Angular 2, handling the observables

查看:21
本文介绍了Angular 2 中的身份验证,处理可观察对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始了一个 Angular 2 项目,正在尝试启动和运行身份验证.受到本教程的启发,我决定执行以下操作:

I just started with a Angular 2 project and am trying to get authentication up and running. Inspired by this tutorial I decided to do the following:

  • 创建自定义 RouterOutlet 类(对其进行扩展)以在调用 url 时处理身份验证逻辑.

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

I succeeded in this custom class, but am still not sure how to check if a user is authenticated. My situation is as follows, I need to query a get call to a external API, for my development proces it is as follows:

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 时调用以下函数吗?:

This API call returns true or false. I was wondering what would be the best option to use this information? Should I for example call the following function each time a URL should be checked?:

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

我无法启动并运行它,因为在使用我作为示例提供的函数时,我的 observable 是未定义的.

I can't get this up and running because my observable is undefined when using the function I gave as example.

推荐答案

问题"在于你的方法是异步的,所以你需要小心使用它的方式和时间.

The "problem" is that your method is asynchronous so you need to be careful the way and when you use it.

如果您想在您的自定义 RouterOutletactivate 方法中使用,您需要利用 observables 和反应式编程.

If you want to use within the activate method of your custom RouterOutlet, you need to leverage observables and reactive programming.

我不知道您想以何种方式查看管理员角色:

I don't know exactly the way you want to check admin roles:

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

为了优化请求,你可以懒惰地(并且只调用一次)调用请求来检查用户是否是管理员:

In order to optimize the request, you could lazily (and only once) call the request to check if the user is admin or not:

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 方法的实现会更简单:

Another approach will be also to load this hint when authenticating the user. This way, the implementation of the activate method would be simplier:

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

这篇关于Angular 2 中的身份验证,处理可观察对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆