Angular 2/4 communication between two component via a shared service

后端 未结 5 1897
不知归路
不知归路 2020-12-11 13:32

I am trying to build a simple shopping cart application. I have two components and a cart service like following.



<         


        
相关标签:
5条回答
  • 2020-12-11 14:07

    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

    0 讨论(0)
  • 2020-12-11 14:07

    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.

    0 讨论(0)
  • 2020-12-11 14:15

    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.

    Dependency injection and hierarchical dependency injection

    0 讨论(0)
  • 2020-12-11 14:23

    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.

    export class cartService{
        private prodCount = 0;
        prodCountCountChange: Subject<number> = new Subject<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);
    
    0 讨论(0)
  • 2020-12-11 14:30

    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()
    export class DataService {
    
      constructor() { }
    
    }
    

    now create a function that holds your data in data.service.ts

    constructor() { }
     public currentData: any;
     storeData(dataFromComponent){
       this.currentData = dataFromComponent;
     }
     getData(){
       return this.currentData; 
     }
    

    now in app.component

     import { DataService } from './data.service';
    
     export class AppComponent {
    
      constructor(private dataService:DataService) {
    
      }
       anytimeSaveData(){
          // to store data in service call storeData function
         this.dataService.storeData("Hello! I have some data here..");
       }
    }
    

    to get data in another component just import our service and call getData function

     export class HomeComponent {
    
      constructor(private dataService:DataService) {
    
      }
          // to get data from service call getData function
         console.log(this.dataService.getData());
    }
    

    Output in console

    Hello! I have some data here..

    Happy Coding

    0 讨论(0)
提交回复
热议问题