In Angular 4 or 2, I want to emit an event from a component to a service which is not related to the component.
After emitting an action will occur and it will be handled in the service. Can someone give me a code example or any alternate solution for that?
Note: The service is not imported in that component and it should not call any of the service methods in the component but the service can call the component method.
You can use a create a new subject in the component and subscribe to that from the service. When you need to trigger the event you can call subject.next(). And the subcription in the service will be updated.
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) {
}
}