Ngif中的Angular HTTP请求 [英] Angular http request in ngif

查看:55
本文介绍了Ngif中的Angular HTTP请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据表,其中一列有一个按钮,该按钮基于该行中的对象打开一个对话框弹出窗口.我试图基于必须每个按钮调用一次的http请求来显示/隐藏该按钮,以确定该按钮是否应为该行显示/隐藏.我建立了这样的网络通话:

I have a table of data and one column has a button in it that opens a dialog popup based on the object from that row. I am trying to show/hide the button based on a http request that has to be called once per button to determine if the button should show/hide for that row. I set up a network call like this:

setupApi() {
  return this.http.get(url);
}

   shouldShowButton() {
      this.service.getJson()
        .subscribe(data => {
          return true;
        }, error => {
          return false;
        });
    }

然后在我的按钮上显示以下内容:

And then on my button I have this:

<button mat-raised-button *ngIf="shouldShowButton() |  async"></button>

如果我的函数返回void,我在ng上报错.

I am getting error on the ng-if saying my function returns void.

推荐答案

我将对其进行一些重组,并在显示之前处理TS中的所有请求.

I would restructure this a bit, and handle all request in the TS before displaying.

阅读您的评论,我们可以收集....

Reading your comments, we can gather....

如果项目数量未知,则可以使用 forkJoin 根据原始数组并行执行所有请求,然后将值添加到要在表中循环的原始数组中在模板中.我会在您的数组中添加一个布尔属性,我们确定是否应该显示按钮,这里称为 showBtn

If you have an unknown amount of items, you can use forkJoin to perform all requests in parallel based on the original array, then add the value to your original array that you are looping in your table in template. I would add a boolean prop in your array, where we determine that should the button be shown or not, here called showBtn

因此,假设您的数据看起来像(添加bool prop之后):

So Let's say your data looks like (after adding the bool prop):

myDat = [
  { name: "name1", showBtn: false },
  { name: "name2", showBtn: false },
  { name: "name3", showBtn: false },
  { name: "name4", showBtn: false }
];

使用数组 map 将请求推送到帮助器数组,然后我们在其上使用 forkJoin ,然后将布尔值添加到原始数组:

Use array map to push requests to a helper array, which we then use forkJoin on, then add the boolean value to your original array:

shouldShowButton() {
  let reqs = [];
  this.myDat.map(btn => reqs.push(this.myService.getJson(btn.name)));

  this.myData = forkJoin(...reqs).pipe(
    map(val => {
      return val.map((curr, i, arr)=> {
        return {... this.myDat[i], showBtn: curr}
      })
    })
  )
}

现在您可以在可观察的 myData 中拥有所有需要的数据,可以在模板中使用它们,例如:

now you have all data you need inside the observable myData, which you can use in the template like:

<tr *ngFor="let item of myData | async">
  <td>
    {{item.name}}
  </td>
  <td>
    <button *ngIf="item.showBtn" (click)="doSomething(item)">Button!</button>
  </td>
</tr>

STACKBLITZ DEMO

STACKBLITZ DEMO

这篇关于Ngif中的Angular HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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