angular - Receiving multiple instances of data from Behavior Subject every time component is initialised -
i have simple router calling service , receiving data behavior subject...when navigate route , comeback receiving multiple values subject...how can destroy observers of subject , create new subject whenever need...? here plunker demo http://plnkr.co/edit/okiljcekskho1zjf5may?p=preview
planning destroy observers of subject in ngondestroy...
ngondestroy(){ this.srvc.destroysubject(); } can please tell me how destroy observers of behaviorsubject?
the behavior expected.
export class sample1 { constructor(public srvc:heroservice) { this.srvc.data.subscribe(data=> { console.log(data); }); this.srvc.getdata(); } } in constructor subscribe srvc.data , because data behaviorsubject returns recent emitted value. initialize data null, therefore @ first there no data.
then in constructor call this.srvc.getdata() causes event emitted , received subscription (the lines before).
if navigate away , back, sample1 initialized again , constructor executed. first thing is subscribes srvc.data. , gets last emitted value received data previous call getdata() (when first navigated heroes).
the next thing call this.srvc.getdata() again emits received data , subscription gets value passed.
workaround
to fix move call this.srvc.getdata(); service instead like
@injectable() export class heroservice { data: behaviorsubject<repairorder> = new behaviorsubject(null); constructor() { this.getdata(); } getdata(){ this.data.next('recieved data'); } destroysubject(){ //alert('hi'); } }
Comments
Post a Comment