在过去的4年里,我正在努力与Angular 1. *一起工作,我正在尝试自学Angular2和TypeScript!无论如何,我在顶级组件中有一个属性,它是来自http源的用户数据,如此...(这是在一个名为 app.ts
的文件中)
import {UserData} from './services/user-data/UserData';
Component({
selector: 'app', // <app></app>
providers: [...FORM_PROVIDERS],
directives: [...ROUTER_DIRECTIVES],
pipes: [],
template: require('./app.html')
})
@RouteConfig([
// stuff here
])
export class App {
// Please note that UserData is an Injectable Service I have written
userStatus: UserStatus;
constructor(private userData: UserData) {
this.userStatus = new UserStatus();
}
ngOnInit() {
this.userData.getUserStatus()
.subscribe(
(status) => {
this.userStatus = status; // I want to access this in my Child Components...
},
(err) => {console.log(err);},
() => {console.log("User status complete"); }
);
}
}
现在我有另一个组件,它是顶级组件的直接子组件,在其中我想访问父组件's property ' userStatus
',这里是孩子......
Component({
selector: 'profile',
template: require('app/components/profile/profile.html'),
providers: [],
directives: [],
pipes: []
})
export class Profile implements OnInit {
constructor() {
}
ngOnInit() {
// I want to have access with the parent App Component, 'userStatus' propety here... I only want to read this property
}
}
现在在Angular1.x中这很简单,因为我可以在我的子控制器中引用 $parent
或( ANTI PATTERN ALERT!!! )我可能很愚蠢地把这些数据放在我的 $rootScope
中 . 在Angular2中访问父级的最佳方法是什么?提前致谢 .
5 回答
有不同的方式:
全球服务
另见
https://github.com/escardin/angular2-community-faq/blob/master/services.md#how-do-i-communicate-between-components-using-a-shared-service
Global Events in Angular 2
Plunker
由父母共享的
服务并注入给孩子
类似于 global service ,但在父代的
providers
或viewProviders
中列出,而不是boostrap(...)
,仅适用于父级的子级 .父母注入孩子并由孩子直接访问
缺点:紧耦合
我有同样的问题,但我解决了不同的问题 . 我不知道这是否是一种很好的方式,但它对我需要的东西很有用 .
我在子组件的构造函数上使用了@Inject,如下所示:
这对我有用,你只需要声明你想要公开的方法或属性 .
就我而言,AppComponent处理路由,我在菜单项中使用徽章来提醒用户新的未读消息可用 . 因此,每当用户阅读消息时,我希望该计数器刷新,因此我调用刷新方法,以便菜单导航中的数字使用新值更新 . 这可能不是最好的方式,但我喜欢它的简单性 .
你可以:
userStatus
参数,并在父组件中使用此组件时提供值:在父母:
注意它们之间的循环依赖关系 .
我制作了一个通用组件,我需要使用它来引用父级 . 这是我想出的:
在我的组件中,我创建了一个@Input:
然后在使用此组件的父级中:
在超级组件中,我可以使用来自父组件的任何内容:
属性:
功能 :
在Angular 6上,我通过构造函数注入父访问父属性 . 不是最好的解决方案,但它有效: