简体   繁体   English

Angular 2-调用其他组件函数

[英]Angular 2 - Call other component function

i'm trying to call another component function from a component. 我试图从一个组件调用另一个组件函数。 This is my constructor : 这是我的构造函数:

    constructor(
        private http: Http,
        private appComponent: AppComponent
        ) {
        this.setUrl();
    }

    setUrl() {
        if (this.appComponent) {
            this.Url = this.appComponent.getEnvironnement();
        } else {
            setInterval(this.setUrl, 1000);
        }
    }

However, when I'm trying to property/function from my appComponent, I get an error saying : appComponent is undefined 但是,当我尝试从我的appComponent获得属性/功能时,出现一条错误消息: appComponent is undefined

Why my component is undefined, even if I initialize it on the beginning ? 为什么即使我在一开始就对其进行初始化,但我的组件仍未定义?

You can use the @Output for other component event binding. 您可以将@Output用于其他组件事件绑定。

Do use @ Input and @ Output instead of the inputs and outputs properties of the @Directive and @Component decorators 不要使用@ Input和@ Output代替@Directive和@Component装饰器的input和output属性

For more information you can visit following URl: https://www.sitepoint.com/angular-2-components-inputs-outputs/ 有关更多信息,您可以访问以下URl: https ://www.sitepoint.com/angular-2-components-inputs-outputs/

Assuming that the non-app component is a child of the app component you could just flow data from the app component down to the child component. 假设非应用程序组件是应用程序组件的子组件,则可以将数据从应用程序组件向下传递到子组件。 Here we have the app component contain the environmentUrl logic. 在这里,我们的应用程序组件包含environmentUrl逻辑。 This is then saved to as environmentUrl. 然后将其保存为environmentUrl。 This is then passed down to the my-child component's url property. 然后将其传递给my-child组件的url属性。 Therefore no need to have the child component access the parent component's function, instead we can just flow the data down from the parent to the child. 因此,不需要子组件访问父组件的功能,相反,我们可以将数据从父组件向下流到子组件。

@Component({
  selector: 'my-app',
  template: `
    <my-child [url]="environmentUrl"></my-child>
  `
})
export class App {
  environmentUrl: string;

  constructor() {
    this.environmentUrl = getEnvironment();
  }

  getEnvironment() {
    return '/some/url';
  }
}

@Component({
  selector: 'my-child',
  template: `
    <div>
      <h2>{{url}}</h2>
    </div>
  `,
})
export class ChildComponent {

  @Input() url: string;

  constructor() {
  }
}

Another advantage of this approach is that the ChildComponent is more reusable. 这种方法的另一个优点是ChildComponent更可重用。 The ChildComponent doesn't know anything about the parent's method and can be used without explicitedly relying on the parent component. ChildComponent对父级方法一无所知,可以在不显式依赖父级组件的情况下使用。

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

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