I need your help. I'm practicing Angular and trying to pass data between components using rxjs. I have 2 components and a service. I'm getting data from an API. My code works, but it's not correct. I manage to get the object from the array and transfer it, but unfortunately, only the first element of the array is extracted. Please tell me how to get different objects by clicking on the button, and not just the first one? Thank you very much
Service
export class CheckboxServiceService {
public allSelectedProducts: BehaviorSubject<ProductModel[]> = new BehaviorSubject<ProductModel[]>([])
sendProductToList(product: any) {
this.allSelectedProducts.next(product);
}
}
ComponentSender
export class ProductsListApiComponent implements OnInit {
products: ProductModel[];
productDifferent: any;
constructor(private apiService: ApiService , private checkboxService: CheckboxServiceService) { }
ngOnInit(): void {
this.apiService.getAllProducts().subscribe(value => this.products = value);
}
addProductToList() {
let currentValue = this.checkboxService.allSelectedProducts.getValue();
this.productDifferent = this.products.find(element => element.id);
currentValue.push(this.productDifferent);
this.checkboxService.sendProductToList(currentValue);
}
}
ComponentReceiver
export class ProductsRecieverComponent implements OnInit {
public selectedProductsList: ProductModel[] = [];
constructor(private checkboxService: CheckboxServiceService) { }
ngOnInit(): void {
this.checkboxService.allSelectedProducts.subscribe(value => {
this.selectedProductsList = value;
})
}
}