将对象内部的值传递给另一个对象

时间:2018-10-20 02:48:02

标签: angular typescript object ionic-framework

我试图在ionic 3的页面之间发送数据,并且这样做是使用一个对象,该对象用于将用户输入存储在对象A内,然后使用this.navParams.get存储在对象B内我的第一个对象中的值。我的问题是我不知道该怎么做。很简单,这就是我要做的所有事情,我在对象A内有一些属性,称为名称,姓氏,年龄和身高,这些属性我想将它们传递到对象B内,以便它们显示。至于错误,这是我尝试时得到的:

Cannot read property 'nome' of undefined

这是我尝试执行的操作:

我的home.html

    <ion-header>
  <ion-navbar>
    <ion-title>
      Ionic Blank
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  The world is your oyster.
  <p>
    If you get lost, the <a href="http://ionicframework.com/docs/v2">docs</a> will be your guide.
  </p>
  <ion-input placeholder="Insira o nome do objeto" [(ngModel)]="myObject.nome"></ion-input>
  <ion-input placeholder="Insira o sobrenome do objeto" [(ngModel)]="myObject.sobrenome"></ion-input>
  <ion-input placeholder="Insira a idade do objeto" [(ngModel)]="myObject.idade"></ion-input>
  <ion-input placeholder="Insira a altura do objeto" [(ngModel)]="myObject.altura"></ion-input>
  <button ion-button full (click)="goPage()">Go Item page</button>

</ion-content>

我的test.html

<!--
  Generated template for the TestPage page.

  See http://ionicframework.com/docs/components/#navigation for more info on
  Ionic pages and navigation.
-->
<ion-header>

  <ion-navbar>
    <ion-title>Test</ion-title>
  </ion-navbar>

</ion-header>


<ion-content padding>
<h1>Nome:{{user.nome}}</h1>
<h1>Sobrenome:{{user.sobrenome}}</h1>
<h1>Idade:{{user.idade}}</h1>
<h1>Altura:{{user.altura}}</h1>
</ion-content>

我的Home.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { TestPage } from '../test/test';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  public myObject ={
      nome: "",
      sobrenome: "",
      idade:"",
      altura:"",

  };
  constructor(public navCtrl: NavController) {

  }
  goPage(){
    this.navCtrl.push(TestPage, {text:this.myObject});
  }
}

我的test.ts

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';

/**
 * Generated class for the TestPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-test',
  templateUrl: 'test.html',
})
export class TestPage {
public text:string;
public user:any = {}; 
  constructor(public navCtrl: NavController, public navParams: NavParams) {
   // Precisely how i store myObject(Object A) inside my Object B(user) this.user = this.navParams.get('myObject');
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad TestPage');
  }

}

1 个答案:

答案 0 :(得分:1)

home.ts

  goPage(){
    this.navCtrl.push(TestPage, {'myObject':this.myObject});
  }

test.ts

  constructor(public navCtrl: NavController, public navParams: NavParams) {
    this.user = this.navParams.get('myObject');
  }