强制函数在加载异步数据后返回属性绑定的值

时间:2017-09-05 13:08:16

标签: angular asynchronous graphql angular2-changedetection property-binding

<cv-radio-button-group class="duration-radios" 
    [radioItems]="getRadioButtons()" 
</cv-radio-button-group>

所以我有这个角度2组件<cv-radio-button-group>这是一个自定义的单选按钮组。单选按钮的数量由属性[radioItems]确定。这一切都在同步环境中起作用。

但现在我在项目中通过调用服务器来实现它,现在它处于异步环境中。 所以在启动时会调用getRadionButtons()函数,而这对服务器的调用仍在进行。并且getRadiobuttons()需要来自服务器的数据才能返回正确数量的单选按钮,因此我无法获得正确的结果。

我可以通过点击其他地方然后点击返回来强制它,强制ngOnInit()运行。

当异步数据完成时,有没有办法强制函数再次返回它?

2 个答案:

答案 0 :(得分:1)

您可以从中采用至少3种不同的方法,但听起来您正在寻找完整的DOM方法,这可以使用*ngIf

对于你的按钮组,你实际上可以用你的函数创建一个逻辑语句来检查渲染之前的返回状态,注意<ng-container>实际上没有生成和DOM:

<ng-container *ngIf="getRadioButtons() && getRadioButtons().length>
  <cv-radio-button-group class="duration-radios" 
    [radioItems]="getRadioButtons()" 
   </cv-radio-button-group>
</ng-container>

在上面的代码中,逻辑状态期望首先getRadioButtons()返回一个项目,并且(假设它的返回将是一个数组)然后确保在渲染之前填充数组。

正如评论中所提到的,通常这种类型的检查最好在您使用Observables(或Promise)的打字稿组件和/或服务中实现。 Angular: Tour of Heroes - Http很好地涵盖了这一点。

承诺的例子:

const promise =
  new Promise((resolve, reject) => {
  // do some async stuff

  if (CONDITION) resolve(DATA);
  else reject(ERROR);
  })
  .then(
  (data) => { console.log(data); },
  (err) => { console.log(err); }
  );

对于组件打字稿component.ts中的示例,您可以像这样添加打字稿:

radioData: any;
isLoaded: false;

getRadioButtons {
  const promise = new Promise((res, rej) => {
    // ... previous radioButtons code ... ends with data.
    res(radioButtonsData) // this sends the data to the promise handlers below
  })
  .then((data) => { this.radioData = data; this.isLoaded = true; })

您可以使用*ngIf="isLoaded",也可以只使用async pipe

有关承诺和更高级别使用的详细使用示例,请查看this link并转到“#34;写下您的第一个承诺&#34;”部分。

答案 1 :(得分:0)

为什么不在[Testing, The, Results] 中致电getRadioButtons(),然后将结果分配给ngOnInit()

假设[radioItems]将返回Observable。

getRadioButtons()

html的

public radioCount;

ngOnInit() {
       this.getRadioButtons().subscribe(
          (data) => {
            this.radioCount = data;
      });
}