I have two components in my code, A and B. Component A contains a form with data that I want to send to component B. However, it seems like component B is not receiving any data.
Here is the code for Component A:
import { MyService } from 'path/myService.service';
@Component({
//blah blah
providers: [MyService]
})
export class ComponentA implements OnInit {
//my form data
constructor(private myServ: MyService) {}
ngOnInit() {
}
onChange(event) {
const data = event.target.value;
this.myServ.changeMessage(data);
console.log("sent");
}
}
And here is the code for Component B:
import { Component, OnInit } from '@angular/core';
import { MyService } from 'path/myService.service';
@Component({
// blah blah
providers: [MyService]
})
export class ComponentB implements OnInit {
recievedData = null;
constructor(private myServ: MyService) {}
// i tried putting this in constructor instead, but it still didn't work
ngOnInit() {
this.myServ.currentMessage.subscribe(message => {
console.log(message);
this.recievedData = message
});
}
}
This is the code for My Service:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class MyService {
private messageSource = new BehaviorSubject(0);
currentMessage = this.messageSource.asObservable();
changeMessage(message) {
this.messageSource.next(message);
}
constructor() { }
}
Although the console log displays "sent" when triggering the onChange method in Component A, the `console.log(message)` never shows up in the subscribe block of Component B. Any suggestions on why this might be happening?