I am learning to build Ionic-2 app, I have a few components which consume services that make an http call and fetch some data, which in turn will be set in component and will finally be displayed in template. I overall understood the flow but I am making some logical mistake while coding it.
My example component:
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
})
}
}
My corresponding service:
@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;
}
}
So the problem here is:
Unless I click Fetch button (which calls getData() function in the component) it will not load the data, somehow in the constuctor of the component the data must be set and not when I call
getData()function. I tried writingthis.items = this.testService.fetchData()this line in the constructor but it doesn't work.This problem further becomes worse when in another component and service I have to append
navparamsent from this FarmList component:let myUrl = 'http://jsonplaceholder.typicode.com/users/' + this.id ;I try to append this.id which is set to received navparam in it's constructor and I get undefinedconstructor (private nextService: NextService, navParams: NavParams){ this.id = navParams.get("param1"); }
I am simply trying to have a list on one page and then clicking on one of the list items will open new page with it's some more details. I am hitting this publically available API: http://jsonplaceholder.typicode.com/users/ and then appending some number to it to get only one object.
What is the correct way to do it?
UPDATE: I could solve the second problem by simply getting navParams in service constuctor and appending it to the url as follows:
@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 ;
...
}
