I am working on angular app. I want to array of objects from one component to another using service. I am using the following link Pass array of int in Angular Route
PassData.html
<div>
<button type="button" [routerLink]="['/receive-data']">Pass Data</button>
</div>
PassData.ts
import ....
@Component({
selector: 'app-PassData',
templateUrl: './PassData.component.html',
styleUrls: ['./PassData.component.css'],
providers: [DataService]
})
constructor( private dataService: DataService) { }
export class PassData {
passObjects : any[] = [{'name': 'John', 'city': 'paris'},{'name': 'Bob', 'city': 'london'}, {'name': 'Grim', 'city': 'paris'}];
passDataToService() {
this.dataService.storePassedObject(this.passObjects);
}
}
ReceiveData.ts
@Component({
selector: 'app-ReceiveData',
templateUrl: './ReceiveData.component.html',
styleUrls: ['./ReceiveData.component.css'],
providers: [DataService]
})
export class ReceiveData implements OnInit {
let selectedProducts = this.DataService.retrievePassedObject();
console.log(JSON.stringify(selectedProducts)); // prints empty array
}
This is angular service
DataService.ts
import { Injectable } from '@angular/core';
@Injectable()
export class DataService {
allPassedData: any[] = [];
constructor() {}
storePassedObject(passedData) {
this.allPassedData = passedData;
}
retrievePassedObject() {
return this.allPassedData;
}
}
Here there are two components, passedData and RecieveData and a service connecting them so data can be passed b/w them. My goal is to pass the data and print the passed data in ReceiveData Component. I am not sure how to structure the angular service when I retrieve the data I find it is empty.
I have registered in app.module.ts
This is app.module.ts
import ...
@NgModule({
declarations: [
PassData,
ReceieveData
],
providers : [
DataService
]
})
export class AppModule { }
I know allPassedData: any[] = []; is making the data empty when I try to access the objects from receiveData it is reassigned to []. But how do I solve this problem?