【问题标题】:function triggered by Html element running before service return response在服务返回响应之前运行的 Html 元素触发的函数
【发布时间】:2018-10-26 02:36:04
【问题描述】:

我有一个显示链接列表的简单组件。每个链接都应根据权限显示\隐藏。为了获得权限集,我应该使用服务。 这是 HTML 的精简版本:

<a *ngIf=isVisible(10) routerLink=".." [queryParams]="{id:'10'}">bla1</a>     
<a *ngIf=isVisible(40) routerLink=".." [queryParams]= "{id:'20'}">bla2</a>        

这是组件:

constructor(private reportService : service) {}

ngOnInit() {
  this.reportService.GetReportsPermissions().subscribe(result => 
    {
      this.reportsPersmissions = result;
    }, error => { console.log(error)});
 }

 isVisible(reportTypeID : ReportType) : boolean
 {
   return typeof this.reportsPersmissions != 'undefined' && 
     this.reportsPersmissions.find(rp => rp.ReportType == 
     reportTypeID).IsPermitted;
 }

问题是当服务还没有响应并且reportsPersmissions未定义时调用isVisible函数。 我可以想到另一种添加选项

*ngIf= reportsPersmissions 

声明为围绕链接列表的容器 div:

<div *ngIf=reportsPersmissions> //Optional - see below
  <a *ngIf=isVisible(10) routerLink=".." [queryParams]="{id:'10'}">bla1</a>     
  <a *ngIf=isVisible(40) routerLink=".." [queryParams]= "{id:'20'}">bla2</a>        
</div>

这是正确的做法还是有更好的方法(最佳实践)?

【问题讨论】:

  • 你是在返回变量的类型,即 boolean 或 int 并试图在 ngIf 中使用它们

标签: angular observers angular-observable


【解决方案1】:

另一种选择是计算NgOnInit 上的isVisible 条件,然后将其作为变量而不是函数放在ngIf 上,这可能会导致性能问题(因为它是在摘要循环中执行的)。

ngOnInit() {
    this.reportService.GetReportsPermissions().subscribe(result => {
        this.reportsPersmissions = result;

        // Iterate over the reports and calculate the isVisible variable here

    }, error => { console.log(error)});
}

*ngIf="report.isVisible"

在你的情况下,我认为这不会导致性能问题,但是看看这个post

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-12
    • 1970-01-01
    • 1970-01-01
    • 2017-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多