[英]typescript accessing component class variable from another component class
I have two components, class ChatPage
and HomePage
. 我有两个组件,类ChatPage
和HomePage
。
Class ChatPage
has a big constructor due to injecting many services, and an array: 由于注入了许多服务, ChatPage
类的构造函数很大,并且有一个数组:
IonicPage()
@Component({
selector: 'page-chat',
templateUrl: 'chat.html',
providers: [ChatService]
})
export class ChatPage implements OnInit, OnDestroy{
msg:any[];
Class HomePage
, which is another component: HomePage
类,它是另一个组件:
@Component({
selector: 'page-home',
templateUrl: 'home.html',
providers: [ChatService]
})
export class HomePage {
chatRoot = ChatPage;
settingsRoot = SettingsPage;
constructor(private chatService: ChatService) {
}
onReset(){
//this.chatRoot.msg = [];
}
}
I want to reset the msg to []
. 我想将味精重置为[]
。
However, in the current state I get a complaint that msg
is not known. 但是,在当前状态下,我抱怨msg
未知。
In the above example, since ChatService is shared by both Components. 在上面的示例中,由于ChatService由两个组件共享。 You can have msg variable in that service and modify it from both components. 您可以在该服务中具有msg变量,并从两个组件中对其进行修改。 This way it is available in both components. 这样,它在两个组件中都可用。
The Other way is using @Input() decorator, if there is a parent component which holds both A and B components. 如果存在同时包含A和B组件的父组件,则另一种方法是使用@Input()装饰器。
You don't initialize ChatPage
or call the component. 您无需初始化ChatPage
或调用组件。 The chatRoot = ChatPage
variable in your example is just a copy of the class definition where msg
was never initialized. 您的示例中的chatRoot = ChatPage
变量只是从未初始化msg
的类定义的副本。
There are multiple ways for components to communicate or share information. 组件可以通过多种方式交流或共享信息。 Refer to this page of the documentation for details and examples. 有关详细信息和示例,请参考文档的此页面 。 Most common methods are: 最常见的方法是:
@Input()
decorator for hierarchical communication between components 使用@Input()
装饰器在组件之间进行分层通信
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.