Reputation: 185
I want to pass a JSON Object to another Page in Ionic 2. I tried like the following, but I get the exception
Cannot read property 'user' of undefined.
Here How to pass data in ionic2 someone asked the same, but it's without a clear, working answer.
var jsonData = JSON.parse(data);
this.navCtrl.push(InfoPage, {jsonData});
InfoPage
export class InfoPage {
jsonData = null;
user = null;
constructor(public navCtrl: NavController, private loadingCtrl: LoadingController, private navParams: NavParams) {
this.jsonData = this.navParams.get("jsonData");
}
ngOnInit()
{
this.user = this.jsonData.user;
console.log(this.user);
}
}
Upvotes: 0
Views: 1124
Reputation: 71951
Not entirely sure, but i would think something like this would work. On the other hand, I would think that using an intermediary service for this will work much better.
On the page you want to send data from:
let jsonData = JSON.stringify(data);
this.navCtrl.push(InfoPage, {jsonData : jsonData});
On the page which retrieves the data:
export class InfoPage {
jsonData = null;
user = null;
constructor(private navParams: NavParams) {
this.jsonData = JSON.parse(this.navParams.get("jsonData"));
}
ngOnInit() {
this.user = this.jsonData.user;
console.log(this.user);
}
}
Let me again mention though, that it's better to store such data in a so called PageService
which will be a singleton throughout your pages. You can use this to send data from one page to another. If you really want to stick with the parse/stringify, then I would expect my solution to work. Be aware that I didn't test it.
A second solution would be the use of a service, which perhaps you can use for other use-cases as well:
export class PageService {
public pageData: any;
}
You should add this service to your root providers array. After that you can use it inside your pages like this:
FirstPage (sender)
export class FirstPage {
private jsonData: any = {user: 'saskia'};
constructor(private pageService: PageService) {}
goToInfoPage(): void {
this.pageService.pageData = this.jsonData;
this.navCtrl.push(InfoPage);
}
}
InfoPage (receiver)
export class InfoPage {
user: string;
constructor(private pageService: PageService) {}
ionViewWillEnter() {
this.user = this.pageService.pageData.user;
console.log(this.user); //saskia
}
}
I'm using the ionViewWillEnter
lifecycle hook, to assure that the data is obtained at the right time
Upvotes: 1