【发布时间】:2016-06-27 23:16:34
【问题描述】:
我正在学习构建 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;
}
}
所以这里的问题是:
除非我点击 Fetch 按钮(它在组件中调用 getData() 函数)它不会加载数据,不知何故在组件的构造函数中必须设置数据,而不是在我调用
getData()函数时设置。我尝试在构造函数中写this.items = this.testService.fetchData()这一行,但它不起作用。-
当在另一个组件和服务中我必须附加从这个 FarmList 组件发送的
navparam时,这个问题会变得更糟:let myUrl = 'http://jsonplaceholder.typicode.com/users/' + this.id ;我尝试附加 this.id 在它的构造函数中设置为接收 navparam,我得到 undefined构造函数(私有nextService:NextService,navParams:NavParams){ this.id = navParams.get("param1"); }
我只是想在一页上列出一个列表,然后单击其中一个列表项将打开新页面,其中包含更多详细信息。我正在点击这个公开可用的 API:http://jsonplaceholder.typicode.com/users/,然后在其上附加一些数字以仅获取一个对象。
正确的做法是什么?
更新:我可以通过简单地在服务构造器中获取 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 ;
...
}
【问题讨论】:
-
您是否尝试过使用ngOninit?
-
不,我不知道。关于如何使用它的任何说明?