我正在开发一个项目,我在服务器上有一个JSON文件,如下所示:
{
"user1": false,
"user2": false,
"user3": false,
"user4": false
}
然后我在我的搜索服务中向服务器发出请求,看起来像这样(但实际的URL在那里):
用户service.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class UserServiceProvider {
data: any;
constructor(public http: Http) {
console.log('Hello UserServiceProvider Provider');
}
loadUserMap(){
return this.http.get(httpUrlToJSON).map(res => res.json()).subscribe(data => {
this.data = data
console.log(data);
})
}
}
每当我在home.ts中调用loadUserMap函数时,数据日志表明它将上面的JSON文件作为对象返回。但是,我不确定如何在我的应用程序中显示和使用这些数据。我试着用以下方式做到这一点:
home.ts
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { HttpModule } from '@angular/http';
import { Http } from '@angular/http';
import {UserServiceProvider} from '../../providers/user-service/user-service';
@Component({
selector: 'page-home',
templateUrl: 'home.html',
providers: [HttpModule, UserServiceProvider]
})
export class HomePage {
public users: Object;
public namesArray;
constructor(public navCtrl: NavController, public userService: UserServiceProvider) {
this.users = this.loadUsers();
this.namesArray = Object.keys(this.users);
}
loadUsers(){
return this.advisorService.loadUsers();
}
}
home.html的
<ion-navbar *navbar>
<ion-title>
Home
</ion-title>
</ion-navbar>
<ion-content class="home">
<ion-list>
<ion-item *ngFor="let user of namesArray">
<h2>{{user}} </h2>
</ion-item>
</ion-list>
</ion-content>
但结果如下:
我如何正确地在应用程序中显示此数据?
答案 0 :(得分:2)
删除服务中的订阅部分。
loadUserMap(){
return this.http.get(httpUrlToJSON).map(res => res.json());
}
订阅您的组件并使用Object.map获取响应结果的键。
loadUsers(){
// advisorService should be advisorService?(a typo?)
this.advisorService.loadUsers().subscribe(data => {
this.users = data;
this.namesArray = Object.keys(data);
});
}
将构造函数更改为仅调用loadUsers
函数:
constructor(public navCtrl: NavController, public userService: UserServiceProvider) {
this.loadUsers();
}
答案 1 :(得分:1)
不要在loadUserMap
内部订阅。只需返回http并在loadUsers
函数
import { Http,Response } from '@angular/http';
loadUserMap(){
return this.http.get(httpUrlToJSON).map((res:Response) => res.json());
}
constructor(public navCtrl: NavController, public userService: UserServiceProvider) {
this.loadUsers();
}
loadUsers(){
this.userService.loadAdvisorMap().subscribe(data => {
this.namesArray = data
console.log(data);
})
}