To facilitate the transfer of data between components, I implemented a service:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class DataTransferService {
private messageSource = new BehaviorSubject<string>("hello");
currentMessage = this.messageSource.asObservable();
constructor() {
}
changeMessage(message: string) {
this.messageSource.next(message);
console.log(message);
}
}
I have created a string variable called messageSource to store the data being passed and currentMessage as an Observable. Additionally, I have included a function to update this data.
Now, in the ngOnInit() method within one of my components, I wrote:
this.data.currentMessage.subscribe(message => this.message = message);
and declared a variable message:string within the component to hold the message.
Within a function, I have added:
selectNews(news) {
this.data.changeMessage("hello3"); // test string
}
Following this, I want to access this string in another component.
Once again, in the ngOnInit(), I executed the same line of code and defined the message. However, the console log shows the string before the function has completed its action....
So where could the problem lie?
Edit Fiddle with complete code :