I want to retrieve an updated object value (borrower) from an Angular Service. I've created an RxJS Subject
in the Service so that multiple components can subscribe to it and get the updated value.
When I subscribe to the Subject through the provided service in the component, I find that the onNext()
function argument is never called even when .next()
is called from BorrowerService.
If I did subscribe within the BorrowerService class, I find that .next()
works as expected. It seems that the Subject is a different instance between the Service class that calls .next()
and the component, and so doesn't get that subscription.
Is this a failing in understanding Angular Services or Observables? How can I update the value in the Service and passively get the changes in the Component without it knowing when to call .next()
?
borrower-report.component.ts
@Component({
...
providers: [BorrowerService]
})
export class BorrowerReport {
private borrower: Borrower;
constructor(private borrowerService: BorrowerService) {
this.borrowerService.borrowerChanged.subscribe(borrower => {this.borrower = borrower});
}
}
borrower.service.ts
@Injectable()
export class BorrowerService {
public borrowerChanged: Subject<Borrower> = new Subject<Borrower>();
//event handler
selectBorrower(borrower: Borrower) {
this.borrowerChanged.next(borrower);
}
}