I am developing an application using angular2. I have a scenario where I need to pass complex data (array of objects) from one component to another component(they are not parent-child, they are two separate components) while routing(using router.navigate()). I have googled this and most of the results describe the scenario of components that are parent-child. I have gone through the results and found these ways to pass the data.
1) Create Shared Service 2) Pass as route parameters
2nd approach works for me (even though, I don't like that when I have complex data as explained above). I am not able to share the data using shared service. So my questions is, does passing data between components using services only works when components are in parent-child relationship? Also, let me know if there are other prefered ways to pass data between one component and other?
Updated: I am adding bit of code from my scenario. Please let me know my mistake as to why passing data through shared services is not working.
I have 2 components: 1) SearchComponent 2) TransferComponent I am setting the data in SearchComponent and want to access the data in TransferComponent through utilityService.
Utility Service:
import {Injectable} from "@angular/core";
@Injectable()
export class UtilityService{
constructor(){
}
public bioReagentObject = [];
routeBioReagentObj(bioReagentObj){
console.log("From UtilityService...", bioReagentObj);
for (let each of bioReagentObj)
this.bioReagentObject.push(each)
// console.log("From UtilityService",this.bioReagentObject);
}
returnObject(){
console.log("From UtilityService",this.bioReagentObject);
return this.bioReagentObject
}
}
searchcomponent.ts
import {UtilityService} from "../services/utilityservice.component";
import {Component, OnInit, OnDestroy, Input} from '@angular/core';
@Component({
selector: 'bioshoppe-search-details',
providers: [UtilityService],
templateUrl: 'app/search/searchdetails.component.html',
styleUrls: ['../../css/style.css']
})
export class SearchDetailsComponent implements OnInit, OnDestroy {
constructor(private route: ActivatedRoute,
private utilityService: UtilityService,
private router: Router) {
}
@Input() selected: Array<String> = [{barcode:123, description:"xyz"}];
//This method is called from .html and this.selected has the data to be shared.
toTransfer() {
this.utilityService.routeBioReagentObj(this.selected);
this.router.navigate(['/transfer']);
}
}
TransferService.ts
import {Component, Input, OnInit, OnDestroy} from '@angular/core';
import {TransferService} from "../services/transferservice.component";
import {UserService} from "../services/userservice.component";
import {SearchService} from "../services/searchservice.component";
import {ActivatedRoute} from '@angular/router';
import {UtilityService} from "../services/utilityservice.component";
@Component({
selector: 'bioshoppe-transfer',
providers: [TransferService, UserService, SearchService, UtilityService],
templateUrl: 'app/transfer/transfer.component.html',
styleUrls: ['../../css/style.css', '../../css/transfer.component.css']
})
export class TransferComponent implements OnInit, OnDestroy{
constructor(private transferService: TransferService,
private userService: UserService,
private searchService: SearchService,
private utilityService: UtilityService,
private route: ActivatedRoute
) {
}
ngOnInit() {
// I am trying to access the data here, but it print "undefind"
console.log("From Transferpage",this.utilityService.returnObject());
}
}
I am sure something is wrong, but it's just that I am not able to figure it out.Any help is appreciated.
In Angular, there are various ways to share data between two components. We are using @Input and @Output variables to share data between parent and child components.
In the case of sharing data from parent to child component, we use props. Props data is shared by the parent component and Child component cannot be changed as they are read-only. Now we will run the application. For Parent, component creates a callback Function and its Function gets the data from the child component.
camaron is right. Your mistake is that you declare UtilityService
twice:
SearchComponent
.TransferComponent
.You should declare the service ONLY ONCE to make sure both components get the same instance. For this you can choose between either of these options:
@NgModule
which has both SearchComponent
and TransferComponent
in its declarations. 9 times out of 10 this is the right solution!@Component
which is a parent of both SearchComponent
and TransferComponent
. This might not be feasible depending how your component tree looks.Following option #1, you end up with:
@NgModule({
imports: [CommonModule, ...],
// Look, the components injecting the service are here:
declarations: [SearchComponent, TransferComponent, ...],
// Look, the service is declared here ONLY ONCE:
providers: [UtilityService, ...]
})
export class SomeModule { }
Then inject UtilityService
in your components' constructors WITHOUT REDECLARING IT in the components's providers:
@Component({
selector: 'foo',
template: '...',
providers: [] // DO NOT REDECLARE the service here
})
export class SearchComponent {
constructor(private utilityService: UtilityService) { }
}
@Component({
selector: 'bar',
template: '...',
providers: [] // DO NOT REDECLARE the service here
})
export class TransferComponent {
constructor(private utilityService: UtilityService) { }
}
You need to distinguish when service is from NgModule, or when it comes from other Component.
Basics
In Angular2 you have a hierarchical tree of components with parent-child relation (as you noticed). At the same time all services are injected with help of injectors, which also form a hierarchy tree (in parallel to component hierarchy). The tree of injectors do not necessary coincide with component tree, as there could be proxy injectors from parent for efficiency purposes.
How it works
The role of the injectors is to take the service you define in constructor and inject it into your component, i.e. find it, initiate if not found and provide it to you. When you put into constructor that you want some service, it will go look into injector tree from your component up to the root (which is NgModule) for service existence. If injector finds that there is a defined provider for this service but no service instance, it will create the service. If no provider it continues to go up.
What you have seen so far
What you have seen is that the parent component defines through "providers" the service, and injectors in search for the service goes one hop up in the tree, finds the provider, initiate service and gives to your child component. In order for all components of some subtree to have the same Service, you need to define provider only in the common root of the subtree. If you want to have same service for whole module, you need define this service in providers of module. This is so-called Singleton service.
Some extra
Normally if you want to inject service and could not find it all the way up to root, you will get error during compilation/runtime. But if you define that you want to inject Optional service, injector will not fail if the provider for this service is not found.
More or less...
Some useful links:
https://angular.io/docs/ts/latest/guide/hierarchical-dependency-injection.html
https://blog.thoughtram.io/angular/2015/05/18/dependency-injection-in-angular-2.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With