I'm new to Observables and still trying to get my head around exactly how they work.
I'm trying to take an array from an observable and allow it to be changed, but without affecting the observable. I thought I'd be able to do this with Object.assign()
The flow is:
- Get an array of invoices from the API.
- Store it as a BehaviorSubject Observable in a service.
- User navigates to 'view all invoices' screen.
- User clicks on 'Edit' one invoice
- Edit component loads, subscribes to the Observable, finds the correct invoice from the array and assigns it to a separate
this.invoiceobject. - User should be able to edit
this.invoicewithout affecting the observable
But no. 6 doesn't work. If the user clicks on Edit invoice, makes a change to the invoice, doesn't save it to the DB but instead goes back to the view invoice screen and clicks edit again, the changes persist. I would expect the original invoice to be shown, not the newly edited one.
In user.service:
export class UserService {
...
public invoices: BehaviorSubject<any> = new BehaviorSubject(null);
...
constructor(){
};
}
Get the invoice array:
userLogin() {
this.commonService.request('login', '', {password: this.password, email: this.email})
.then((response:any) => {
...
if(response.invoiceData) this.userService.invoices.next(response.invoiceData);
...
}
})
}
View invoices component:
ngOnInit() {
this.invoicesSubscription = this.userService.invoices.subscribe((invoices) => {
if(invoices) {
this.invoices = invoices;
}
});
}
Edit invoice component:
ngOnInit() {
this.paramsSubscription = this.activatedRoute.params.subscribe((params: Params) => {
if(params) {
this.invoicesSubscription = this.userService.invoices.subscribe((invoices) => {
if(invoices) {
invoices.forEach((invoice) => {
if(invoice._id == params.invoiceId) {
this.invoice = Object.assign({}, invoice);
console.log(invoice) // This shows changes to the invoice when the screen loads for the second time.
}
});
}
});
}
});
}
How can I edit this.invoice object without the changes affecting the Observable?