您可以使用在组件中创建新主题并从服务订阅该主题。当您需要触发事件时,您可以调用 subject.next()。并且服务中的订阅也会更新。
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { TestComponent } from './test.component';
import {AppService} from './app.service';
@NgModule({
declarations: [
AppComponent,
TestComponent
],
imports: [
BrowserModule
],
providers: [AppService],
bootstrap: [AppComponent]
})
export class AppModule { }
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { AppComponent } from './app.component';
@Injectable()
export class AppService {
constructor() {
AppComponent.getSubject().subscribe((response) => {
this.doSomething(response);
});
}
public doSomething(response): void {
console.log('Event triggered', response);
}
}
import { Component } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
private static subject = new Subject<string>();
public static getSubject(): Observable<string> {
return AppComponent.subject.asObservable();
}
public onClick(): void {
AppComponent.subject.next('Test');
}
}
import { Component } from '@angular/core';
import { AppService } from './app.service';
@Component({
selector: 'app-test',
template: `<div>test component</div>`
})
export class TestComponent {
constructor(private appService: AppService) {
}
}