I work on Angular 4, onclick of one of the 'groups' its tile should be added to the list of 'favourites' (which is an array). For this I used BehaviorSubject. I am able to display default message on my FavouriteComponent.html but when I click on newMessage() from GroupComponent.ts the value in FavouriteComponent.html is not changing it remains default message. Please guide me where I went wrong or is there any other way to achieve my requirement.
DataService.ts
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")
}
}