Utilize behavior subjects to simplify the process in this scenario.
Create a shared Service file that can be accessed throughout the application.
In the shared service file, implement the following:
@Injectable({
providedIn: 'root'
})
export class CommonService {
initialValuesForProductsArray: string[] = [];
productsArraySource: BehaviorSubject<string[]> = new BehaviorSubject<string[]>(this.initialValuesForProductsArray);
productsArrayObservable: Observable<string[]> = this.productsArraySource.asObservable();
constructor() {}
setProductsArray(data: string[]) {
this.productsArraySource.next(data);
}
getProductsArray(): Observable<string[]> {
return this.productsArrayObservable;
}
}
Within your component, follow these steps:
export class ProductComponent implements OnInit {
***
addedToCart: Item[] = [];
constructor(
private data: DataService,
private commonService: CommonService <<<<<<<<<<< ADD THIS LINE >>>>>>>>
) { }
addToCart(product:Item){
***
}
ngOnInit(): void {
this.data.getData()
.subscribe(
response =>{
this.products = response;
this.commonService.setProductsArray(this.products); <<<<<<< ADD THIS LINE >>>>>>
}
)
}
}
To retrieve this data within another component, do the following:
export class CartComponent implements OnInit {
cartItems:Item[] | undefined;
constructor(private commonService: CommonService) {} <<<<< ADD THIS LINE >>>>
ngOnInit(): void {
<<<<<<<< ADD BELOW LINES >>>>>>>>
this.commonService.getProductsArray().subscribe(data => {
if (data && data.length) {
this.cartItems = data;
}
});
}
}
This is how you can effectively use behavior subjects to manage data flow between components.