Add to compare service for observable array of objects for products

Add to compare service for observable array of objects for products.

import { Injectable } from ‘@angular/core’;
import { BehaviorSubject } from ‘rxjs/BehaviorSubject’;

@Injectable()
export class SharedService {

compareProducts:Array<Product> = [];
private compareSource = new BehaviorSubject<Product[]>([]);
currentCompare = this.compareSource.asObservable();

constructor() {
}

addToCompare(productModel){
var index = this.compareProducts.findIndex(item => item.id === productModel.id);
if(index > -1){
this.compareProducts.splice(index,1);
}else{
this.compareProducts.push(productModel);
}
//orders.splice(index, 1);

this.compareSource.next(this.compareProducts);
console.log(this.compareProducts);
}

}
export class Product{
id?: any;
product_id?: any;
attachments?:any;
attributes?: any;
category_id?:any;
currency?: any;
currency_id?: any;
description?: any;
discount?: any;
discount_amount?:any;
highlights?:Array<any>;
images?: any;
is_active?: any;
image?: any;
min_order_qty?: any;
name?: any;
price?: any;
product_attributes?:any;
product_code?:any;
reviews?: any;
reviews_count?: any;
show_price?: any;
}

Subscribe this currentCompare to get the current array of products into compare.

addToCompare do work like toggle here if we found the object in this compareProducts array we do remove it from here and if we dont find it here we do add it here.

Remember We are adding and removing whole productModel.

Calling in a component.

this.sharedService.currentCompare.subscribe(res=>{ this.compareProducts = res; });