[英]How can i access the values from parent component in angular2 using dependency injection?
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 我有两个组件,一个父母和一个孩子,我想从孩子使用DI访问父组件中的变量,但我没有得到那个。我做了一个plunker演示http://plnkr.co/edit/fcfweLJAmadKVWKXF25l?p=preview ...我试图从child访问变量的值并且正确地得到但不是从父到子。这就是我在子组件中访问变量的方式
@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);
}
}
I want to know is it possible to access variable from parent using DI? 我想知道是否可以使用DI从父级访问变量? some body please tell me how to get the values
请告诉我如何获取价值观
Yes, it's possible but you need to leverage forwardRef
as described below because you can't use hoisting: 是的,这是可能的,但你需要利用
forwardRef
如下所述,因为你不能使用吊装:
@Inject(forwardRef(() => AppComponent)) app:AppComponent
Here is the complete sample: 这是完整的样本:
@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 {
}
Here is the updated plunkr: http://plnkr.co/edit/brmQ01wFWrWvXmxpJpCc?p=preview . 这是更新的plunkr: http ://plnkr.co/edit/brmQ01wFWrWvXmxpJpCc?p = preview。
This article written by Christoph Burgdorf could also help you: 这篇由Christoph Burgdorf撰写的文章也可以帮助你:
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... 如果将类定义到单独的模块/文件中,我们还应该注意循环依赖:父组件导入子组件1,子组件导入父组件...
You would have to inject a service in parent component (in providers entry), set the value you want to use and than use it in child component. 您必须在父组件中注入服务(在提供程序条目中),设置要使用的值,而不是在子组件中使用它。
@Component({
selector: 'app',
providers:[YourService]
template: '<childCmp></childCmp>'
})
class AppComponent {
constructor(private yourService: YourService) {
this.yourService.setData(data);
}
}
@Component({
selector: 'childCmp',
template: '{{yourService.getData()}}'
})
class ChildCmp {
constructor(private yourService: YourService) {
this.yourService.setData(value);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.