I have been facing difficulties passing an array from one component to another. The issue arises when the array is passed between components and ends up being empty. Despite seeing integers in the console, the array is being passed before any values are pushed into it. After trying various approaches and conducting extensive research, I discovered that using BehaviorSubject
as outlined in this discussion would be the best solution: Angular 4 pass data between 2 not related components
The only challenge is that the example given focuses on passing a string, while my requirement is to pass an integer array instead. We need to find a suitable example similar to the mentioned one but tailored for passing integer arrays. The service.ts
acts as the shared service between compA
and compB
. In this case, compA
is the component that should receive the array from compB
, which holds the necessary array for passing to compA
. So, which component should subscribe to the BehaviorSubject
? Below is a simplified snippet of my code with commented lines indicating my progress towards implementing BehaviorSubject
with an array.
Shared Service - service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@http';
import { BehaviorSubject } from 'rxjs/BehaviourSubject';
import { RootService } from '../../../common/root-service/root.service';
@Injectable()
export class service {
//dataSource: BehaviorSubject<Array<number>> = new BehaviourSubject([]);
//dataPlot = this.userDataSource.asObservable();
dataPlot: Array<number> = [];
constructor(private http: HttpClient, private appRootService: RootService) { }
... Some Code ...
/**
updateDataPlot(data) {
this.dataSource.next(data);
}
*/
setDataPlot(data: Array<number>) {
this.dataPlot = data;
}
getDataPlot(): Array<number> {
return this.dataPlot;
}
}
ComponentA - compA.ts
import { Component, HostListener } from '@angular/core';
import { service } from '../../..common/service';
... Some Code...
@Component({
selector: 'compA',
styleUrls: ['./compA.css'],
templateUrl: './compA.html'
})
export class compA {
... Some Code ...
dataPlotArray: Array<number>;
constructor(private sw: Service){
this.getDataPlot();
}
... Some Code ...
getDataPlot() {
this.dataPlotArray = this.sw.getDataPlot()
}
... Rest of Code ...
ComponentB - compB.ts
import { Component, HostListener } from '@angular/core';
import { service } from '../../..common/service';
... Some Code...
@Component({
selector: 'compB',
styleUrls: ['./compB.css'],
templateUrl: './compB.html'
})
export class compB {
... Some Code ...
dataPlot: Array<number> = [];
constructor(private sw: Service){
this.setDataPlot();
}
... Some Code ...
/**
setDataPlot() {
this.sw.setDataPlot.subscribe((this.dataPlot) => {
this.sw.updateDataPlot(this.dataPlot);
})
}
*/
setDataPlot() {
this.sw.setDataPlot(this.dataPlot);
}
... Rest of Code ...