假设我有3个角分量,第一个分量使用第二个和第三个分量作为指令。它们应该共享同一个模型对象,该模型对象在第一个组件中初始化。如何将该模型传递给第二个和第三个组件?我提到了这个帖子How to pass object from one component to another in Angular 2?,但它使用的是输入..。我想知道在各个子组件之间共享模型对象的所有可能的备选方案,请告诉我可以遵循的选项。
发布于 2016-02-02 06:05:12
将类型添加到First组件的提供程序列表中,并将其注入到First的构造函数、涉及的子构造器和外孙构造器中。
@Component({
...
providers: [SharedService]
})
export class First {
constructor(private shared: SharedService);
// also add this parameter to the other child and grand-child
// component and directives constructors and they will get
// passed a shared instance.
}不要将SharedService添加到任何一个子实例或全局子程序providers中,否则它们会得到一个新实例而不是共享实例。
如果将SharedService添加到bootstrap(AppComponent, [SharedService])而不是父组件,则整个应用程序共享seam SharedService实例,而不是只共享选定的子树。
发布于 2016-02-02 23:52:01
在子节点(而不是共享服务)上使用输入属性的一个优点是,角度变化检测将自动将更改传播到子节点。如果您使用的是不可变对象,并且希望更改整个模型(将其转换为新的实例/引用),这尤其有用。
使用服务,您可以更改模型,但不能更改模型引用。
对于输入属性,您可以这样做:更改模型和/或更改模型引用。
有关使用不可变数据建模的更多信息,请参见以下Savkin博客文章:http://victorsavkin.com/post/133936129316/angular-immutability-and-encapsulation
https://stackoverflow.com/questions/35146108
复制相似问题