Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 如何根据用户角色隐藏内容?_Angular_Typescript_Firebase_Google Cloud Firestore_Observable - Fatal编程技术网

Angular 如何根据用户角色隐藏内容?

Angular 如何根据用户角色隐藏内容?,angular,typescript,firebase,google-cloud-firestore,observable,Angular,Typescript,Firebase,Google Cloud Firestore,Observable,在我的身份验证服务中,我有一个可观察的用户,该用户从firebase后端填充 我还有一个方法,它接受user对象,如果用户具有传入的角色,则返回一个布尔值 在我的模板中,我有一些元素,我只想在登录用户的admin角色被列为他们的角色之一时显示这些元素。我需要它以这样的方式运行,我最终可以使用is('contributor')等,并且仍然可以得到一个布尔值 现在,当我尝试测试它时,浏览器挂起并最终崩溃。如果用户的角色与需求匹配,我如何设置div直到数据解析为止 // authService

在我的身份验证服务中,我有一个可观察的
用户
,该用户从firebase后端填充

我还有一个方法,它接受user对象,如果用户具有传入的角色,则返回一个布尔值

在我的模板中,我有一些元素,我只想在登录用户的
admin
角色被列为他们的角色之一时显示这些元素。我需要它以这样的方式运行,我最终可以使用is('contributor')等,并且仍然可以得到一个布尔值

现在,当我尝试测试它时,浏览器挂起并最终崩溃。如果用户的角色与需求匹配,我如何设置div直到数据解析为止

// authService

  this.user = this.afAuth.authState.pipe(
    switchMap(user => {
      if (user) {
        return this.afs.doc<User>(`users/${user.uid}`).valueChanges()
      } else {
        return of(null)
      }
    })
  )

is(role){
    let p = Promise

    this.user.toPromise().then(resolvedUserData=>{
    (_.has(role, resolvedUserData.roles)) ? p.resolve() : p.reject(); 
   })

   return p;
  }


 //template

 <div *ngIf="authService.is('admin') | async">admin content here</div>
//authService
this.user=this.afAuth.authState.pipe(
开关映射(用户=>{
如果(用户){
返回此.afs.doc(`users/${user.uid}`)。valueChanges()
}否则{
返回(空)
}
})
)
is(角色){
让p=承诺
this.user.toPromise().then(resolvedUserData=>{
(u.has(role,resolvedUserData.roles))?p.resolve():p.reject();
})
返回p;
}
//模板
管理内容在这里

您的函数正在返回一个承诺,异步管道需要一个可观察的

//授权服务

isAdmin = false;

this.user = this.afAuth.authState.pipe(
switchMap(user => {

  if( check if use is admin){
      this.isAdmin = true;
  }
})
)

//模板

 <div *ngIf="authService.isAdmin">admin content here</div>
这里的管理内容

现在,从安全角度来看,我不确定这是最好的方法。我会有一些其他类型的验证或令牌。但这种方法回答了你的问题。干杯。

这改变了我所不需要的功能。我对这个问题做了更多的澄清。为什么要将可观察的转换为承诺,然后使用异步管道?那么就使用observable吧。看看jhipster生成的应用程序是如何处理这一点的,它们使用has authority指令,在基于角色隐藏/显示元素时总是帮我做这件事:您可以在is(角色)函数中添加一个变量,并将其设置为false,在承诺得到解决后将其设置为true。在您的div中,检查该变量,并仅在其为true时显示&autoService.si('admin')为true。我相信如果第一条语句是假的,它不会检查第二条语句,所以第二条语句不会使页面崩溃。