0

I'm trying to create Cart functionality in my MOBILE POC (Cordova2/Angular2). I've created Service for share data between components. I'adding items through Component A and trying to read from Component B. But I'm not seeing those items in Component B. What should I add in Service?

import { Injectable  } from '@angular/core';    
@Injectable()    
export class CartService {
    private vijayCart: Array<any> = [];
    GetCart() {
        return this.vijayCart;
    }
    SetCart(item) {
        this.vijayCart.push(item);
    }
}  

Component A:

addItemToCart(item) {
    this.cartService.SetCart(item);
    //this.cartService.vijayCart.push(item);
    this.cartLenth = this.cartService.GetCart().length;
}

Component B:

  ngOnInit(): void {
      this.cartSer = this.cartService.GetCart();
  }
user3194721
  • 675
  • 4
  • 12
  • 35

1 Answers1

1

Everything is correct one thing you are missing is to provide the service to both the components. you need to share the service at module level to say that my service is shared between these two components.

 providers: [AppService],

the entire code of module

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [AppService],
  bootstrap: [AppComponent]
})
export class AppModule { }

if you want to go into more detail and want to know how to share data between two modules you can see share data between tow module

Behaviour subject Behaviour subject is a better way to share data between components and it handles future data sharing when ever there is a data change in one service, it notifies the other service.

to see in details you can see this sharing data between components

Aniruddha Das
  • 14,517
  • 13
  • 83
  • 111