【发布时间】:2018-01-23 09:49:27
【问题描述】:
这是我第一次使用 Ionic 3 和 Angular 5。
我想简单调用一个 rest api,并将结果显示在一个列表中。
我看到有必要创建一个提供程序,负责进行调用。
在google中导航,看到一个例子,我的provider是:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
//import 'rxjs/add/operator/map'
/*
Generated class for the PeopleServiceProvider provider.
See https://angular.io/guide/dependency-injection for more info on providers
and Angular DI.
*/
@Injectable()
export class PeopleServiceProvider {
dati : string
constructor(public http: HttpClient) {
console.log('Hello PeopleServiceProvider Provider');
}
load() {
if (this.dati) {
// already loaded data
return Promise.resolve(this.dati);
}
// don't have the data yet
return new Promise(resolve => {
// We're using Angular HTTP provider to request the data,
// then on the response, it'll map the JSON data to a parsed JS object.
// Next, we process the data and resolve the promise with the new data.
this.http.get('https://randomuser.me/api/?results=10')
//.map(res => res.json())
.subscribe(data => {
// we've got back the raw data, now generate the core schedule data
// and save the data for later reference
console.log(data);
this.dati = data["results"];
resolve(this.dati);
});
});
}
}
然后我有了我的模板,一切正常。我的问题更令人怀疑。
当我从 api 得到响应时,要获取结果,我必须这样做:
data["results"]
我认为我能够做到:
data.results
我错过了什么吗?谢谢!
【问题讨论】:
-
你从哪里得到这个例子的?请看这里angular.io/guide/http
-
我解决了创建界面的问题,但这是唯一的方法吗?对不起,这是第一次,我想澄清我所有的疑问。谢谢!!!
-
如果你的数据是一个对象,你应该可以通过
data["results"]或data. result来检索结果,我们可以看看你的服务器响应吗? -
链接的文档有你的问题的答案...
-
@YounesM 我在网上使用了一个假的 api:randomuser.me/api/?results=10