davidvera
davidvera

Reputation: 1489

Angular 6 - Sending an object between component using a Service

Actually I'm confronted to 2 issues with Angular. My first consists on adding articles in a basket in different component. I send an object to a service and a second component retrieve it ...

My second issue is when i want to have a second product, i wish to display both of them and not overwritting it. I have been reading this : http://jasonwatmore.com/post/2018/06/25/angular-6-communicating-between-components-with-observable-subject in order to give me some skills ...

In my view i added a button :

<button class="btn btn-danger" (click)="onAddProduct()">Ajouter</button>

Here is my article component :

export class ProductComponent implements OnInit {
   @Input() private product: Product;
   private basketData: BasketdataService;

   constructor(private basketData: BasketdataService) {  }

   ngOnInit() {
   }
   onAddProduct() {
     console.log(this.product);
     this.basketData.onAddBasket(this.product);
   }
}

My service here retrieve the datas and share them with the basket component

export class BasketdataService {
  private subject = new Subject<any>();

  onAddBasket(product: Product) {
    this.subject.next(product);
  }

  onGetBasket(): Observable<Product> {
    return this.subject.asObservable();

  }
  removeArticleBasket() {
    this.subject.next();
  }

Here is my basketComponent

export class BasketmenuComponent implements OnInit, OnDestroy {
  product : Product;
  subscription : Subscription;

  constructor(private basketdataService: BasketdataService) {
    this.subscription = this.basketdataService.onGetBasket().subscribe(message => { this.product = product; });
  }
  ngOnInit() {
  }
  ngOnDestroy() {
    // unsubscribe to ensure no memory leaks
    this.subscription.unsubscribe();
  }
}

I receive this error : ERROR ReferenceError: product is not defined at SafeSubscriber._next

Upvotes: 0

Views: 37

Answers (1)

rikg93
rikg93

Reputation: 1269

In basketComponent you've an error, try this:

export class BasketmenuComponent implements OnInit, OnDestroy {
  product : Product;
  subscription : Subscription;

  constructor(private basketdataService: BasketdataService) {
    this.subscription = this.basketdataService.onGetBasket().subscribe(product=> { this.product = product; });
  }
  ngOnInit() {
  }
  ngOnDestroy() {
    // unsubscribe to ensure no memory leaks
    this.subscription.unsubscribe();
  }

}

It's not "message", but "product" in this.subscription

Upvotes: 1

Related Questions