安装
ng g service event
Angular会自动在项目的app目录下生成 event.service.ts 和 event.service.spec.ts 两个文件。
我们在 event.service.ts 文件中完成相关业务代码即可。
event.service.ts :
import { Injectable } from '@angular/core';
import {Observable,Subject} from "rxjs";
@Injectable({
providedIn: 'root'
})
export class EventService {
// 构建Subject的实例,用来完成事件的发布和订阅
private renderSubject = new Subject < any > ();
constructor() {}
public getRenderSubject(): any {
return this.renderSubject;
}
public emitRenderInfo(msg: any): void {
if (msg) {
this.renderSubject.next(msg);
}
}
}
在app.modules.ts文件中注册我们的服务
app.modules.ts:
在子组件1中 注册并使用
chid1.ts 注册
import {EventService} from "../../event.service";
import {Subscription} from "rxjs"
constructor(private eventService: EventService, ) {}
private renderChartSubscription: Subscription = null;
ngOnInit(): void {
if (!this.renderChartSubscription) {
this.renderChartSubscription= this.eventService.getRenderSubject()
.subscribe((res: any) => {
console.log("==")
console.log(res)
});
}
// this.initMap()
}
chid2.ts 调用
this.eventService.emitRenderInfo("0099");