简体   繁体   English

无法访问ngOnInit函数的参数窗体构造函数

[英]Can't access params form constructor for ngOnInit function

I'm passing params in Ionic 3 to a component. 我正在将Ionic 3中的参数传递给组件。 I understand that you pull the params in the constructor of the recieving page, but I'm having trouble accessing them in the pages ngOnInit. 我了解您在接收页面的构造函数中提取了参数,但是在ngOnInit页面中访问它们时遇到了麻烦。

So my constructor looks like this: 所以我的构造函数看起来像这样:

  constructor(public navCtrl: NavController, public navParams: NavParams, private contactsProvider: ContactsProvider) {
    let contactId = this.navParams.get('contactId');
    let ownerId = this.navParams.get('ownerId');

    // this.contactsProvider.getContact(ownerId, contactId)
    //   .subscribe(response =>{
    //    this.contact = response.json();
    //    console.log('Response: ', this.contact);
    //   })

  }

and my Init looks like this: 我的初始化看起来像这样:

 ngOnInit(){
    this.contactsProvider.getContact(ownerId, contactId)
    .subscribe(response =>{
     this.contact = response.json();
     console.log('Response: ', this.contact);
    })
  }

I get a TS error saying that 'ownerId' does not exist on the page. 我收到一条TS错误,提示页面上不存在'ownerId'。

What am I doing wrong here. 我在这里做错了。

Thanks for any input!! 感谢您的输入!

It needs to be 它必须是

this.contactId = this.navParams.get('contactId');
this.ownerId = this.navParams.get('ownerId');

otherwise the value will only be available inside the constructor. 否则,该值将仅在构造函数内部可用。

And also here 还有这里

ngOnInit(){
    this.contactsProvider.getContact(this.ownerId, this.contactId)

Variables declared in your constructor are local variables , only availables from the constructor() . 在构造函数中声明的local variableslocal variables ,仅可从constructor() You have to declare them as Component properties to be able to use them everywhere in your component, this way : 您必须将它们声明为Component属性,以便能够在组件中的任何地方使用它们,方法是:

@Component({...})
private contactId: number;
private ownerId: number;
...

And then you can use them in your component methods, using this as Günter show you : 然后你就可以在你的组件方法中使用它们,用this作为冈特告诉你:

constructor(public navCtrl: NavController, public navParams: NavParams, private contactsProvider: ContactsProvider) {
  this.contactId = this.navParams.get('contactId');
  this.ownerId = this.navParams.get('ownerId');

}


ngOnInit(){
    this.contactsProvider.getContact(this.ownerId, this.contactId)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM