关于html:使用API??数据调用ngFor的问题

Issue calling ngFor with API data

我试图在我的离子应用程序中显示数据库调用中的所有元素,但出现以下错误:

1
Error: Cannot find a differ supporting object 'Response with status: 200 OK for URL: http://url/getAllProvs' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

下面是我要用API数据填充的html代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<ion-header>
  <ion-navbar>
    <button ion-button clear (click)="logout()">
      <ion-icon name="log-out"></ion-icon>
    </button>
    <ion-title>All Patients</ion-title>
  </ion-navbar>
</ion-header>

<ion-content class="all-patients">
  <ion-list>
    <button ion-item *ngFor="let item of data1">
      {{item.firstName}}
    </button>
  </ion-list>
</ion-content>

下面是邮递员获取数据请求的图片:
enter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
export class AllPatientsPage {
  data1: any;
  loading: any;
  isLoggedIn: boolean = false;

  constructor(public app: App, public loadingCtrl: LoadingController, private toastCtrl: ToastController, public navCtrl: NavController, public restService: RestService){
    this.getAllProvs();
    if(localStorage.getItem("token")) {
      this.isLoggedIn = true;
    }
  }

    getAllProvs(){
        this.restService.getAllProvs()
        .then(data => {
            console.log("all-patients.ts data");
            console.log(data);
            this.data1 = data;
        }).catch(e => {
            console.log(e);
        });
    }
}

下面是rest-services方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
export class RestService {

 data1: any;
  constructor(public http: Http) {
    console.log('Hello RestServiceProvider Provider');
  }

    getAllProvs(){
        if(this.data1){
            return Promise.resolve(this.data1);
        }
        return new Promise(resolve => {
            this.http.get('http://url/getAllProvs')
            .subscribe(data => {
                console.log("rest-services.ts subscribe");
                this.data1 = data;
                console.log(data);
                resolve(this.data1);
            });
        });
    }
}


我确实在您的代码中看到了几个问题。

  • 由于要异步获取数据,因此data1最初将是未定义的对象,而*ngFor将引发错误。
    一种方法是简单地将初始值设置为空数组。

    1
    data:any[]=[];
  • 为了将Observable转换为Promise构造,请在此处检查我的答案。使用Observable.toPromise()


  • 您可以尝试将json数据转换为数组,然后使用它。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     getBooks()
          {
            this.isbnsource.getBooks(this.isbn).subscribe(
              data => { this.foundBooks = data.json();
         this.foundBooks = Array.of(this.foundBooks);
               },
              err => console.error(err),
              () => console.log('getBooks completed')
              );
         }

    在这里找到答案