简体   繁体   English

无法在Angular 4 Ionic 3中的html中显示数组对象

[英]Cannot display array objects in html in angular 4 ionic 3

My array structure in my application 我的应用程序中的数组结构

I get above array structure in my application and then I assign it to my variable as follows: 我在应用程序中获得了上面的数组结构,然后将其分配给变量,如下所示:

     `
    .subscribe(data => (
        this.user = data,
        console.log('rain', this.user)
    ));`

but I am not able to display it in HTML. 但我无法以HTML显示它。 I tried to display following way 我试图显示以下方式

` <ion-option  *ngFor="let users of user">{{users[0].pentad1.
 rainfall}}</ion-option>
               </ion-select> `

Can some one please help me with this?? 有人可以帮我吗?

您需要使用* ngFor而不是For才能将其显示为HTML

In the api file use promise, 在api文件中使用promise,

 get_pentad1(param){
    return new Promise( resolve => {
      this.http.method(url, param)
        .subscribe(
          data => {
            resolve(data);
          },
          error => {
            resolve(error.statusText);
          }
        );
    });
  }

use .then() function to get the response from the api as 使用.then()函数从api获取响应

this.api.get_pentad1(param).then(data => { this.user = data[0] } ); 

Try the following code: 尝试以下代码:

TS File: TS文件:

public user : any = [];


.subscribe((data)=>{
      this.user = data;
  });

HTML: HTML:

<ion-select>
    <ion-option *ngFor="let users of user">

     <span *ngIf="users && users.pentad1"> {{users.pentad1.rainfall}}</span>
     <span *ngIf="users && users.pentad2"> {{users.pentad2.rainfall}}</span>
    </ion-option>
  </ion-select>

You might have to change "pentad1" and "pentad2" in order to be consistent just a suggestion 您可能需要更改“ pentad1”和“ pentad2”以保持一致,这只是一个建议

From your Array structure, to display the rainfall, I would suggest you to use a pipe. 从数组结构中,要显示降雨量,建议您使用管道。

Run the following command to generate a pipe 运行以下命令以生成管道

 ionic generate pipe rainfall

What is a pipe? 什么是管道?

In your component 在你的组件中

...
public users : any = [];
...
.subscribe(res => {
    this.users = res;
 });

transform function in the pipe 管道中的变换功能

transform(value: string, index: number) {
    const key = `pentad${index+1}`;
    return value[key].rainfall;
}

In your html 在你的HTML

<ion-select>
    <ion-option *ngFor="let user of users; let i = index;" [value]="user">{{user | rainfall: i}}</ion-option>
</ion-select>

Note: Put the PipesModule in the imports array of your components module. 注意:PipesModule放入组件模块的imports数组中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM