I have been struggling with passing an array from one component to another. The issue is that when the array is pass between components it is empty. I can see in the console that the array is filled with integers, but it is being pass before any values are push into it. I have tried multiple things and after an extensive research found that the best approach would be to use BehaviorSubject
as describe in this thread: Angular 4 pass data between 2 not related components
The only thing is that in the example provided they are passing a string. I have been trying to find another good example like the one mentioned above but instead of passing strings it would need to be an integer array. service.ts
is the shared service between compA
and compB
. compA
is the component that needs to receive the array from compB
. compB
is the component that has the array needed to be pass to compA
. With that being said, which component would need to subscribe to the BehaviorSubject
? A simplified version of my code is given below with the commented lines being what I have come up with so far to implement BehaviorSubject
with an array.
Shared Service - service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/http';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { RootService } from '../../../common/root-service/root.service';
@Injectable()
export class service {
//dataSource: BehaviorSubject<Array<number>> = new BehaviorSubject([]);
//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 ...