如何在Angular组件之间进行通信? [英] How to communicate between component in Angular?
本文介绍了如何在Angular组件之间进行通信?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在开发一个Web应用程序项目,并且尝试使用Angular,在组件通信方面遇到了一些问题.例如,父组件如何与子组件交换数据,兄弟姐妹组件之间如何通信.
I'm working on a web app project and I'm trying to use Angular, I get some problem with component communication. For example, how a parent component exchange data with child component, how to communicate between siblings components.
推荐答案
使用服务:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class AppState {
public _subject = new Subject<object>();
public event = this._subject.asObservable();
public publish(data: any) {
this._subject.next(data);
}
}
,您可以发布类似事件的消息:
and you can publish event-like messages like this:
export class AppComponent {
constructor(
public appState: AppState
) {
appState.publish({data: 'some data'});
}
}
,您可以订阅以下事件:
and you can subscribe to these events:
export class HomeComponent {
constructor(
public appState: AppState
) {
appState.event.subscribe((data) => {
console.log(data); // {data: 'some data'}
});
}
}
这篇关于如何在Angular组件之间进行通信?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文