我如何可以访问父组件中使用angular2依赖注入的价值观? [英] How can i access the values from parent component in angular2 using dependency injection?

查看:190
本文介绍了我如何可以访问父组件中使用angular2依赖注入的价值观?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个组件上的一个家长和一个孩子,我想使用DI孩子访问父组件的变量,但我没有得到that.i已经取得了plunker演示的 http://plnkr.co/edit/fcfweLJAmadKVWKXF25l?p=$p$pview ...我试图访问的值从子变量,然后从父child.This了corrrectly而不是如何我正在访问的子组件变量

I have two components one parent and a child i want to access a variable in parent component from child using DI but i am not getting that.i have made a plunker demo http://plnkr.co/edit/fcfweLJAmadKVWKXF25l?p=preview ... I tried to access the value of variable from child and got corrrectly but not from parent to child.This is how i am accessing variable in child component

@Component({
  selector: 'child',
  providers:[AppComponent]
  template: '<h1>My second Angular 2 App</h1>'
})
class NameComponent {
  name:string;
  constructor(AppComponent: AppComponent) {
    this.name = AppComponent.getName();
    console.log(this.name);
  }
}

我想知道的是有可能使用DI从父访问的变量?一些身体请告诉我如何获取值

I want to know is it possible to access variable from parent using DI? some body please tell me how to get the values

推荐答案

是的,这是可能的,但你需要利用 forwardRef ,如下所述,因为你不能使用吊装

Yes, it's possible but you need to leverage forwardRef as described below because you can't use hoisting:

@Inject(forwardRef(() => AppComponent)) app:AppComponent

下面是完整的示例:

@Component({
  selector: 'child',
  providers:[AppComponent]
  template: '<h1>My second Angular 2 App</h1>'
})
class NameComponent {
  name:string;
  constructor(@Inject(forwardRef(() => AppComponent)) appComponent: AppComponent) {
    this.name = appComponent.getName();
    console.log(this.name);
  }
}

@Component({
})
class AppComponent {
}

下面是更新plunkr: http://plnkr.co/edit/brmQ01wFWrWvXmxpJpCc p = preVIEW

Here is the updated plunkr: http://plnkr.co/edit/brmQ01wFWrWvXmxpJpCc?p=preview.

本文章由克里斯托夫·布格多夫写也可以帮助你:

This article written by Christoph Burgdorf could also help you:

我们也应小心,循环依赖,如果类定义成单独的模块/文件:父组件进口孩子之一和儿童一台进口父1 ...

We should also be careful of cyclic dependency if classes are defined into separate modules / files: the parent component imports the child one and the child one imports the parent one...

希望它可以帮助你,
蒂埃里

Hope it helps you, Thierry

这篇关于我如何可以访问父组件中使用angular2依赖注入的价值观?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆