我正在学习如何构建Ionic-2应用程序,我有几个组件使用使用http调用和获取一些数据的服务,这些数据将被设置在组件中并最终显示在模板中。我总体理解流程,但在编写代码时,我犯了一些逻辑错误。
我的示例组件:
export class FarmList {
items: Object;
constructor(private testService: TestService, public nav: NavController){}
getData(): any {
this.items = this.testService.fetchData()
}
nextView(){
this.nav.push(Farm)
}
showDetails(id: Number){
this.nav.push(Farm, {
param1: id
})
}
}我的相应服务:
@Injectable()
export class TestService{
loading: boolean;
data: Object;
constructor(private http: Http){
let myUrl = 'http://jsonplaceholder.typicode.com/users';
this.loading = true;
this.http.request(myUrl)
.subscribe(
(res: Response) => {
this.loading=false;
this.data=res.json();
});
}
public fetchData(){
return this.data;
}
}应用程序的屏幕截图:

这里的问题是:
getData()函数时设置数据。我试着在构造函数中编写这一行this.items = this.testService.fetchData(),但是它不起作用。navparam组件发送的FarmList时,这个问题就变得更糟了:let myUrl = 'http://jsonplaceholder.typicode.com/users/' + this.id ;,我尝试在它的构造函数中追加this.id,它被设置为received,而我得到了未定义的
构造函数(私有nextService: NextService,navParams: NavParams){ this.id = navParams.get("param1");}我只是尝试在一个页面上有一个列表,然后点击其中的一个列表项目将打开新的页面,这是一些更多的细节。我点击这个公开可用的API:http://jsonplaceholder.typicode.com/users/,然后给它附加一些数字,只得到一个对象。
,什么是正确的方法?
更新:I可以通过简单地在服务构造器中获取navParams并将其附加到url中来解决第二个问题,如下所示:
@Injectable()
export class NextService{
loading: boolean;
data: Object;
id: Number;
constructor(private http: Http, navParams: NavParams){
this.id = navParams.get("param1");
console.log("Second service fetching param: " + this.id)
let myUrl = 'http://jsonplaceholder.typicode.com/users/' + this.id ;
...
}发布于 2016-06-27 23:55:09
ngOnInit可能是您要寻找的内容:
import { OnInit} from '@angular/core';
...
export class FarmList implements OnInit {
...
ngOnInit(){
this.getData()
}
}在角度阅读更多内容
编辑:
由于你的评论,我再看看你的电话在做什么。在组件中,您将数据设置为从fetchData函数返回的任何数据,该函数只返回服务中设置的数据。在调用ngOnInit时,它只是一个空对象,几毫秒后,service.data被更改为从http异步调用返回的任何内容。
更好的做法是遵循角的Http入门教程。从本质上说,我认为你最终会得到更像这样的东西:
服务:
@Injectable()
export class TestService{
private myUrl: string = 'http://jsonplaceholder.typicode.com/users';
// loading: boolean;
//move any logic that has to do with UI to the component...
//this is more of a suggestion and has to do with MV* best practices
constructor(private http: Http){
// I think it was in John Papa's Pluralsight video on angular 2 that said
// try to do as little as possible inside of the constructor
}
public fetchData(){
//the key here is to return a promise (or observable) so that the
//component can handle it when it gets resolved
return this.http.get(myUrl)
.toPromise()
.then(response => response.json().data)
}
}组件:
import { OnInit} from '@angular/core';
...
export class FarmList implements OnInit {
...
ngOninit(){
this.getData()
}
getData(){
this.testService.fetchData().then(data => this.items = data)
}
}https://stackoverflow.com/questions/38064676
复制相似问题