I am leaing to build Ionic-2 app, I have a few components which consume services that make an http call and fetch some data, which in tu 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(){
retu this.data;
}
}
So the problem here is:
-
Unless I click Fetch button 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 navparam as received in it's constructor and I getundefined
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?

