Angular 2/4 Communication Between Two Component Via A Shared Service
Solution 1:
In this case, You can use a service with subject
. A service in Angular is a singleton, meaning it is managed as a single instance. So if each of the components access the service, they will access the same shared data.
exportclasscartService{
private prodCount = 0;
prodCountCountChange: Subject<number> = newSubject<number>();
UpdateCount(count: number) {
this.prodCount = count;
this.prodCountCountChange.next(this.prodCount);
}
}
In your component you can do this,
this._cartService.UpdateCount(this.prod.length);
Solution 2:
In the header, you must subscribe to some event in the Shared Service
. The same event will be emitted from your cart component.
Please have a look at this plunkr https://plnkr.co/edit/LS1uqB?p=preview
Solution 3:
You should use Subject
from RxJs
. In your cart you will subscribe to some counter in your service so you'll able to update cart information in app-header
.
Solution 4:
In angular the components will share an instance of a service if it is from the same ancestor. For example you have your app-header
and app-cart
wich are part of the AppModule
. So if you add SharedCartService
to the providers
array of your module, the two components will get the same instance of that service.
Solution 5:
Create a service by :-
ng g service data
Upon running this, your output may look something like
installing service
create src\app\data.service.spec.ts
create src\app\data.service.ts
WARNING Service is generated but not provided, it must be provided to be used
The warning simply means that we have to add it to the providers property of the NgModule decorator in src/app/app.module.ts, so let's do that:
import { DataService } from'./data.service';
@NgModule({
providers: [DataService],
})
Now that we have created a service, let's take a look at what the Angular CLI created:
import { Injectable } from'@angular/core';
@Injectable()
exportclassDataService {
constructor() { }
}
now create a function that holds your data in data.service.ts
constructor() { }
publiccurrentData: any;
storeData(dataFromComponent){
this.currentData = dataFromComponent;
}
getData(){
returnthis.currentData;
}
now in app.component
import { DataService } from'./data.service';
exportclassAppComponent {
constructor(private dataService:DataService) {
}
anytimeSaveData(){
// to store data in service call storeData functionthis.dataService.storeData("Hello! I have some data here..");
}
}
to get data in another component just import our service and call getData function
exportclassHomeComponent {
constructor(private dataService:DataService) {
}
// to get data from service call getData functionconsole.log(this.dataService.getData());
}
Output in console
Hello! I have some data here..
Happy Coding
Post a Comment for "Angular 2/4 Communication Between Two Component Via A Shared Service"