我需要从Angular 2中的其他组件获取公共方法

时间:2016-10-12 13:51:14

标签: javascript angular typescript

我需要从app.component调用headerExpand属性,但是当我尝试制作它时,请在控制台中告诉我:

  

metadata_resolver.js:559未捕获错误:“Page1”的提供程序无效 - 只允许提供者和类型的实例,得到:[?undefined?]

page1.ts

<pre>
import { Component } from '@angular/core';
import { MyApp } from '../../app/app.component';

@Component({
  selector: 'page-page1',
  templateUrl: 'page1.html',

})
export class Page1 {

  constructor(public miApp: MyApp) {
    console.log(miApp.headerExpand);

  }

</pre>

app.component.ts

<pre>
@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  @ViewChild(Nav) nav: Nav;

  rootPage: any = Page1;
  public headerExpand: boolean;
  public pages: Array<{title: string, component: any}>;

  constructor(public platform: Platform) {
    this.initializeApp();
    this.headerExpand = true;


  }

  initializeApp() {
    this.platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      StatusBar.styleDefault();
    });
  }

  openPage(page) {
    // Reset the content nav to have just this page
    // we wouldn't want the back button to show in this scenario
    this.nav.setRoot(page.component);
  }



  expandHeader(){
    this.headerExpand = false;
  }
}

1 个答案:

答案 0 :(得分:1)

无法注入父组件到子组件。你应该例如在此方案中使用输出()(子项为父项)。看看这里:

https://angular.io/docs/ts/latest/cookbook/component-communication.html