首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular 5 Observable需要等待,直到它被竞争

Angular 5 Observable需要等待,直到它被竞争
EN

Stack Overflow用户
提问于 2018-07-12 05:35:12
回答 0查看 1.5K关注 0票数 0

在调用checkPermissions()方法之前,我需要等到getPermissions()可观测对象完成。但无论如何我都不能得到它...

我也试过使用async/await,但似乎对我也不起作用?

我需要我的权限,然后我才能检查它们,对吧。有什么想法?

如果有更好的办法,我洗耳恭听。

非常感谢。

代码语言:javascript
复制
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot } from '@angular/router';
import { AuthService } from './auth.service';

@Injectable()
export class RoleGuardService implements CanActivate {
  
  constructor(public auth: AuthService,public router: Router) { }

  canActivate(route: ActivatedRouteSnapshot): boolean {
    //This will be passed from the route config, on the data property
    const expectedRole = route.data.expectedRole;
    var hasPerm = this.loadAndCheckPermissions(expectedRole);

    console.log('done! ' + hasPerm);
    return hasPerm;
  }

  loadAndCheckPermissions(expectedRole) {
    var hasPermission = false;
    localStorage.clear();
    var myPermissions = localStorage.getItem('user-permissions');
    
    if (myPermissions === null) {
      console.log("PERMISSIONS from Server!");

      //You can't wait for an Observable or Promise to complete.
      //You can only subscribe to it to get notified when it completes or emits an event.
      this.auth.getPermissions()
        .subscribe(res => {
          localStorage.setItem('user-permissions', JSON.stringify(res.body));

          //Check permissions now
          //hasPermission = this.checkPermissions(expectedRole);
        });
    } else {
      hasPermission = this.checkPermissions(expectedRole); 
    }

    console.log('loadAndCheckPermissions ' + hasPermission);
    return hasPermission;
  }

  //Check a permission here
  checkPermissions(expectedRole) {
    return this.auth.checkPermission(expectedRole);
  }
}

EN

回答

页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51294491

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档