Reputation: 9457
I'm using AngularJs 1.5. I am using ng-route to create a SPA. For 2 templates I have used the new Angular component as the template let's call them 'employee' and 'company'. Within each route there is a sub component that searches the company database call it companySrch. How the sub component works is the companySrch component is loaded in either 'company' or 'employee' when the user want's to search the company database within that template. When the user selects a record in the search results, the record is broadcast through a registered RXJS observable as follows:
companySrch.getRecordFn = function(result){
companySrch.output={id:result.cs_id, type:result.type,name:result.name, active: result.active};
//BROADCAST RECORD SELECTED via companySrchService
companySrch.companySrchService.recordBroadcast(companySrch.output);
companySrch.navService.nav.navExt = false;
}
Then if the user is in employee or company template, that record is passed through the template's subscription to the RXJS event. Example for both templates employee and company respectively:
employee.companySrchService.subscribe(function(obj) {//SELECTRECORD IS PASSED VAR FROM BROADCAST FUNCTION
//GET COMPANY RECORD UPON BROADCAST
employee.submit[0].cs_name = obj.name;
employee.submit[0].cs_type = obj.type;
employee.submit[0].fk_cs_id = obj.id;
//employee.getRecordFn(obj.id);
});
company.companySrchService.subscribe(function(obj) {//SELECTRECORD IS PASSED VAR FROM BROADCAST FUNCTION
//GET COMPANY RECORD UPON BROADCAST
company.getRecordFn(obj.id);
});
The issue I have when I am in the employee template and a companySrch record is broadcast the subscribed event also is fired in the 'company' on the assumption I have previously loaded the company template. As such this causing an error. I thought components are killed completely when templates are switched?? Is there any way I can prevent the RXJS subscribe event from occurring if the template is not in view??
Upvotes: 2
Views: 2389
Reputation: 3104
We can create a Subject that will emit as soon as the directive's $destroy
event is triggered.
var destroy$ = new Rx.Subject();
$scope.$on('$destroy', () => destroy$.onNext());
And we can update the stream that we subscribe to so that we stop emitting items as soon as destroy$
emits once:
company.companySrchService
.takeUntil(destroy$)
.subscribe(function(obj) {
company.getRecordFn(obj.id);
});
This will cause your subscription callback to stop firing as soon as the $destroy
event occurs.
Upvotes: 4