验证在角2,处理观测 [英] Authentication in Angular 2, handling the observables

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

问题描述

我刚开始用角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被调用。

我成功地在这个自定义类,但我仍然不知道如何检查,如果用户进行身份验证。我的情况是这样的,我需要查询get调用到一个外部API,为我发展PROCES其计算方法如下:

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

我不能得到这个启动和运行,因为我观察到的用我给的例子中,函数时,是不确定的。

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.

如果您想自定义的激活方法中使用 RouterOutlet ,你需要利用观测和无功节目。

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

另一种方法也将是验证用户时加载此提示。这样,激活方法的实现将是simplier:

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

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

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