I have two components. In one component there is check boxes. I want the value of checked items to display on another page's component when user click on change page. in component 2 when user click get checked items, then i retrieve value from shared service to display. But the value is empty.
I have read some solution on stack overflow but it does not work.here
How to solve this?
component 1 button
<button (click)="changePage()">Change page</button>
component 2 button
<button (click)="getChecked()">Get checked items</button>
shared.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class SharedService {
checkedItems:any[];
checkedList=new BehaviorSubject<any>([]);
constructor() {
}
setCheckedList(val:any[]){
this.checkedItems=val;
this.checkedList.next(this.checkedItems);
}
getCheckedItems():BehaviorSubject<any>{
return this.checkedList;
}
}
Component 1
changePage(){
this.checkedIDs = []
this.checkboxesDataList.forEach((value, index) => {
if (value.isChecked) {
this.checkedIDs.push(value.id);
}
});
this.sharedService.setCheckedList(this.checkedIDs);
this.router.navigate(['/list']);
}
checkboxesDataList = [
{
id: '1',
label: 'name',
isChecked: true
}
]
Component 2
getChecked(){
this.items=this.sharedService.getCheckedItems();
console.log(this.items)
}
CodePudding user response:
for getting values from BehaviorSubject, you must call the getValue().
in shared.service.ts, update to
getCheckedItems():BehaviorSubject<any>{
return this.checkedList.getValue();
}
CodePudding user response:
You can get the last value set to the BehaviourSubject
using getValue().
getChecked() {
this.items = this.sharedService.checkedList.getValue();
}