In my Angular 4 project, there is a functionality where upon clicking on one of the 'groups', its tile should be added to a list of 'favourites' which is represented as an array. To implement this feature, I utilized a BehaviorSubject
. While I am able to display the default message
on my FavouriteComponent.html
, I encountered an issue when attempting to update the value upon calling the newMessage() function from GroupComponent.ts
. The displayed value in FavouriteComponent.html
remains unchanged and still shows the default message
. I would appreciate guidance on identifying where I might have made a mistake or if there is an alternative approach to achieve the desired behavior.
Below are excerpts from the code:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class DataService {
private messageSource = new BehaviorSubject("default message");
currentMessage = this.messageSource.asObservable();
constructor() { }
changeMessage(message: string) {
this.messageSource.next(message)
}
}
FavouriteComponent.ts
import { DataService } from "../data.service";
@Component({
selector: 'app-parent',
template: `
{{message}}
`
})
export class FavouriteComponent implements OnInit {
message:string;
constructor(private data: DataService) { }
ngOnInit() {
this.data.currentMessage.subscribe(message => this.message = message)
}
}
GroupComponent.ts
import { DataService } from "../data.service";
@Component({
selector: 'app-sibling',
template: `
{{message}}
<button (click)="newMessage()">New Message</button>
`,
styleUrls: ['./sibling.component.css']
})
export class GroupComponent implements OnInit {
message:string;
constructor(private data: DataService) { }
ngOnInit() {
this.data.currentMessage.subscribe(message => this.message = message)
}
newMessage() {
this.data.changeMessage("new title to add")
}
}