使用@Input Angular 2在类之间传递数据

时间:2016-03-04 16:00:24

标签: angular

我在这里是一个菜鸟,但我需要一些帮助,我正在做一个Ionic 2应用程序,这是关于搜索,所以我有一个主模板,我将插入一个新的模板与结果' s,所以我有问题fot将搜索关键字从主模板传递到结果模板,我正在尝试@Input,但我是一个菜鸟,我想学习,我将非常感谢你的帮助......

这是主要代码App.html我的变量是" prueba":

<div id="sbar">
 <ion-searchbar id="searchbox" (keyup)='upkey($event)' (keydown)='downkey($event)' [recibir]="prueba" //here i declare the bindding variables></ion-searchbar>
</div>

这是我的App.js代码,我在其中分配搜索关键字:

class MyApp {
  constructor(app: IonicApp, platform: Platform, http: Http) {
   this.app = app;
   this.platform = platform;
   this.http=http;

   this.prueba = "Search_Key"; //my variable

   this.Leyes = [];
   this.url = 'http://##########/resultados.json?q='; 
   this.initializeApp();

   this.pages = [
     { imagen: 'build/img/home.png', title: 'Home', component: GettingStartedPage },
     { imagen: 'build/img/info38.png', title: 'Ayuda', component: AyudaHTML },
     { imagen: 'build/img/faq7.png', title: 'Preguntas Frecuentes', component: FaqHTML }
     { imagen: 'build/img/cloud158.png', title: 'Actualizaciones', component: ActualizacionesHTML },
     { imagen: 'build/img/news29.png', title: 'Novedades', component: NovedadesHTML },
     { imagen: 'build/img/two205.png', title: '¿Te gustaría colaborar?', component: ColaborarHTML },
     { imagen: 'build/img/multiple25.png', title: 'Acerca', component: AcercaHTML},
     ];
  this.rootPage = GettingStartedPage;
  }

  initializeApp() {
  this.platform.ready().then(() => {
  });
}

这是我收到名为&#34; recibir&#34;的输入的另一个模板:

export class GettingStartedPage{
    @Input() recibir;//this the Search_key that I receive
    constructor(app: IonicApp,http: Http) {
        this.http=http;
        this.Leyes = [];
        this.url = 'http://www.##########/resultados.json?q='; 
        alert("Recibira :" + this.recibir);
        this.buscar(this.recibir);
    }
 }

请帮助我...它不起作用我不知道为什么

2 个答案:

答案 0 :(得分:1)

构造函数中尚未提供输入值。

请改用ngOnInit()。调用ngOnInit()时,Angular完成初始化组件并重新绑定绑定。

export class GettingStartedPage{
    @Input() recibir;//this the Search_key that I receive
    constructor(app: IonicApp,http: Http) {
        this.http=http;
        this.Leyes = [];
        this.url = 'http://www.##########/resultados.json?q='; 
    }

    ngOnInit() {
        alert("Recibira :" + this.recibir);
        this.buscar(this.recibir);
    }
 }

另见

答案 1 :(得分:0)

我决定使用它:

export class GettingStartedPage implements OnInit{

constructor(app: IonicApp,http: Http) {

this.http=http;
this.Leyes = [];
this.url = 'http://www.leybook.com/resultados.json?q='; to  
this.val = app.getComponent('searchbox').value;(<--- This gets the value directly of "searchbox" in my main template, This worked for me)
alert(this.val);
}
ngOnInit(){    
  this.buscar(this.val); 
}
}

我希望能帮助像我这样的其他菜鸟....(Y)