我正在学习Ionic并遇到问题。我的应用陷入了循环,反复从远程服务器获取信息并导致浏览器崩溃。
我在下面的代码中设置了一项服务来检索数据:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
/*
Generated class for the CategoriesServiceProvider provider.
See https://angular.io/guide/dependency-injection for more info on providers
and Angular DI.
*/
@Injectable()
export class CategoriesServiceProvider {
apiURL = 'https://reqres.in/api/users';
constructor(public http: HttpClient) {
console.log('Hello CategoriesServiceProvider Provider');
}
getUsers(){
return new Promise(resolve => {
this.http.get(this.apiURL).subscribe(data => {
resolve(data);
// console.log(data);
}, err => {
console.error(err);
});
});
}
}
以下是我的 categories.ts 文件中使用上面服务的代码:
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { CategoriesServiceProvider } from '../../providers/categories-service/categories-service';
/**
* Generated class for the CategoriesPage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
@IonicPage()
@Component({
selector: 'page-categories',
templateUrl: 'categories.html',
providers: [CategoriesServiceProvider]
})
export class CategoriesPage {
constructor(public navCtrl: NavController, public navParams: NavParams, private categories: CategoriesServiceProvider) {
}
users: any;
getUsers(){
this.categories.getUsers().then(data => {
this.users = data;
console.log(this.users);
});
}
ionViewDidLoad() {
console.log('ionViewDidLoad CategoriesPage');
this.getUsers();
}
}
...,后跟 categories.html :
<ion-header>
<ion-navbar>
<ion-title>categories</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-list>
<ion-item *ngFor="let user of getUsers()">
TESTING - {{user.gender}}
</ion-item>
</ion-list>
</ion-content>
我不知道为什么为什么要重复http请求而不是一次获取然后消失。
答案 0 :(得分:0)
在这里循环使用该函数来获取数据:
<ion-content padding>
<ion-list>
<ion-item *ngFor="let user of getUsers()">
TESTING - {{user.gender}}
</ion-item>
</ion-list>
</ion-content>
将其替换为检索到的数据!
类似的东西:
<ion-content padding>
<ion-list>
<ion-item *ngFor="let user of this.users">
TESTING - {{user.gender}}
</ion-item>
</ion-list>
</ion-content>