Skip to content

Instantly share code, notes, and snippets.

@redeemefy
Last active April 18, 2020 03:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save redeemefy/c727f7c1174b4bee95d0caf3a55a9467 to your computer and use it in GitHub Desktop.
Save redeemefy/c727f7c1174b4bee95d0caf3a55a9467 to your computer and use it in GitHub Desktop.
Communication Between Siblings Components Angular
// src/app/messaging.service.ts
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class MessagingService {
private subject = new Subject()
constructor() { }
emitMessage(msg: any) {
this.subject.next(msg)
}
readMessage() {
return this.subject.asObservable()
}
}
// src/app/service/service-edit/service-edit.component.ts
import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { ServiceApi } from '../service.api';
import { MessagingService } from 'src/app/messaging.service';
@Component({
selector: 'app-service-edit',
templateUrl: './service-edit.component.html',
styleUrls: ['./service-edit.component.css']
})
export class ServiceEditComponent implements OnInit {
constructor(private http: HttpClient, private api: ServiceApi, private msgService: MessagingService) { }
ngOnInit(): void { }
private serviceAdded: string = 'service-added'
private httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
}
serviceSubmit(form: NgForm) {
this.api.addService(form)
.subscribe(
response => console.log(`RESPONSE: ${response}`),
error => console.log(`:::: ERROR :::: Error adding new service. ${error}`),
() => this.msgService.emitMessage(this.serviceAdded) // emits the message
)
}
}
// src/app/service/service-edit/service-list.component.ts
import { Component, OnInit } from '@angular/core';
import { Service } from '../service.model'
import { HttpClient } from '@angular/common/http';
import { ServiceApi } from '../service.api';
import { MessagingService } from 'src/app/messaging.service';
@Component({
selector: 'app-service-list',
templateUrl: './service-list.component.html',
styleUrls: ['./service-list.component.css']
})
export class ServiceListComponent implements OnInit {
allServices: Service[]
constructor(private http: HttpClient, private api: ServiceApi, private msgService: MessagingService) {
// listening for the emitted message
this.msgService.readMessage().subscribe(msg => {
console.log(msg)
if(msg === 'service-added') {
this.getAllServices() // fetch if a new service was added
}
})
}
ngOnInit(): void {
this.getAllServices()
}
private getAllServices() {
this.api.fetchAllServices().subscribe(responseData => {
this.allServices = responseData
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment