I have an angular 2 project, in which I have a couple of components. One of the components keeps track of a member (that is the aforementioned BehaviorSubject) using a subscription.
The BehaviorSubject's value is updated and pushed when a user clicks a button.
However, when subscribing, the only value ever pushed is the original value (that is 0).
The Navbar component is the subscriber, where in CountService the BehaviorSubject is declared.
My CountService:
@Injectable()
export class CountService {
private count:number;
public countObservable:BehaviorSubject<number>;
public savedItems = { campaigns: [], news: [] };
constructor (private http: Http) {
this.count=0;
this.countObservable = new BehaviorSubject<number>(this.count);
this.countObservable.next(this.count);
}
keep(keepId: string, type: string){
!!this.savedItems[type].length ?
this.savedItems[type].find(i => i == keepId).length ?
console.log('exist') : this.keepInSavedItems(keepId, type)
this.keepInSavedItems(keepId, type);
}
keepInSavedItems(keepId, type){
this.savedItems[type].push(keepId);
this.count++;
this.countObservable.next(this.count);
}
}
My Navbar Component:
@Component({
selector: 'navbar',
templateUrl: './navbar.component.html',
providers: [ CountService ]
})
export class NavigationbarComponent implements OnInit {
count:number;
constructor(public countService: CountService){
this.count=0;
}
ngOnInit() : void {
this.countService.countObservable.subscribe( count => this.count=count);
}
}