1

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)
  }
Vikash Mishra
  • 319
  • 3
  • 11
  • `this.router.navigate(['/list']);` what the use of showing value in another page if you are just going to navigate away – vaira Dec 13 '21 at 06:45
  • 'getChecked()', do you only wanted the selected item when the user click on this button, not otherwise? – vaira Dec 13 '21 at 06:46
  • 1
    I found answer [here](https://stackoverflow.com/questions/39325503/how-to-pass-data-between-two-components-in-angular-2) – Vikash Mishra Dec 13 '21 at 07:03

2 Answers2

0

for getting values from BehaviorSubject, you must call the getValue().

in shared.service.ts, update to

getCheckedItems():BehaviorSubject<any>{
   return this.checkedList.getValue();
}
Omid Aiene
  • 11
  • 2
0

You can get the last value set to the BehaviourSubject using getValue().

getChecked() {
    this.items = this.sharedService.checkedList.getValue();
}
Deepak
  • 2,660
  • 2
  • 8
  • 23