Dependency injection 从Angular2中的子组件访问父组件数据/属性
我“束手无策”,不知道该怎么办。我快哭了 在使用AngularJS多年之后,我正在努力自学Angular2——我有一个Angular2应用程序,它有顶级组件,比如所谓的应用程序Dependency injection 从Angular2中的子组件访问父组件数据/属性,dependency-injection,typescript,angular,Dependency Injection,Typescript,Angular,我“束手无策”,不知道该怎么办。我快哭了 在使用AngularJS多年之后,我正在努力自学Angular2——我有一个Angular2应用程序,它有顶级组件,比如所谓的应用程序 @Component({ selector: 'app', // <app></app> providers: [...FORM_PROVIDERS], directives: [...ROUTER_DIRECTIVES], template: require('.
@Component({
selector: 'app', // <app></app>
providers: [...FORM_PROVIDERS],
directives: [...ROUTER_DIRECTIVES],
template: require('./app.html')
})
@RouteConfig([
{path: '/', component: Home, name: 'Home'},
{path: 'about', component: About, name: 'About'},
{path: 'profile', component: Profile, name: 'Profile'},
{path: 'profile/:id', component: ForeignProfile, name: 'ForeignProfile'}
])
export class App {
userStatus: UserStatus;
userOnlineContacts: UserContact[];
constructor(private userData: UserData) {
this.userStatus = new UserStatus();
}
ngOnInit() {
Observable.forkJoin([
this.userData.getUserStatus(),
this.userData.getContacts()
]).subscribe( (t) => {
this.userStatus = t[0];
this.userOnlineContacts = t[1].onlineContacts;
});
// Polling thing for this.userOnlineContacts...
this.userData.pollContacts().subscribe(
(data) => {
this.userOnlineContacts = data.onlineContacts;
});
}
}
在此组件中,我希望访问应用程序组件的属性,例如this.userStatus
和this.userOnlineContacts
。我不想创建一个服务来进行重复的HTTP调用,我想将父属性直接注入子属性。在AngularJS中,我可以使用类似于$scope.$parent.userStatus
的东西。现在,我通过修改组件将父应用程序注入子应用程序(ForeignProfile):
这是ForeignProfile组件
import {App} from '../../app'
@Component({
// blah blah...
})
export class ForeignProfile implements OnInit {
// code removed for example, easier to read
userStatus: any;
constructor(private userData: UserData, private routeParams: RouteParams, @Inject app:App) {
// code removed for example, easier to read
this.userStatus = app.userStatus;
}
然后和父母一起
import {Injectable, Component} from 'angular2/core';
@Injectable()
@Component({
selector: 'app', // <app></app>
从'angular2/core'导入{Injectable,Component};
@可注射()
@组成部分({
选择器:'应用',//
这让我的控制台发疯了。有人能解释一下我是如何从我的ForeignProfile组件中的应用程序组件访问属性的吗?到目前为止,我在这方面已经浪费了好几个小时!提前谢谢。正如@Günter Zöchbauer正确提到的,为了在组件之间共享数据,你必须使用angular services概念 如果您仍然想访问应用程序组件,您可以在ForeignProfile构造函数中这样做:
constructor(@Host() @Inject(forwardRef(() => App)) app: App)
{
}
只要使用共享服务在父级和子级之间进行通信就可以了。有很多类似的问题。@GünterZöchbauer,这就是为什么
$scope
如此有用的原因。这让共享服务的任何使用者负责利用其API所需的逻辑。这不适合于干编程。应该有一个合理的方法父组件在不知道实现细节的情况下向任何子组件提供数据。(例如,vm.someProperty.someMethod(someVar)
)这应该得到支持,IMO。如果你使用$scope
,你需要一些契约,以便客户端使用预定义的名称访问一个值。这就是服务类的用途,一个通用的契约。我认为这是正确的方法。但在类似Java的语言中就是这样做的。在JS世界中,这是不常见的,但目前有一个很强的转变从动态语言到类型化语言的ack。这很好,我假设我从“angular2/core”导入@Host
、@Inject
和forwardRef
。
import {Injectable, Component} from 'angular2/core';
@Injectable()
@Component({
selector: 'app', // <app></app>
constructor(@Host() @Inject(forwardRef(() => App)) app: App)
{
}