0

I am passing values from one component to another component having dynamic form but in that component , value is not being received. I am not getting if I am doing anything wrong in passing values to dynamic forms or is this not the way dynamic forms can receive the value.

I have not pasted whole code otherwise it will be too big, so I have mentioned only relevant pieces of code. Please let me know if any more clarification is required.

In AdminService , this is service class where subject is defined as below:

startedEditingItem=new Subject<string>();    

In ProductItemsComponent , value is sent as below to another component.

onEdit(index:number){
    console.log("on edit"+this.productId+":"+this.childProductId+":"+index)// This is being printed , so value is sent
    this.adminService.startedEditingItem.next(this.productId+":"+this.childProductId+":"+index);}

In ItemEditComponent , value is subscribed as below

ngOnInit() {
    console.log("edit item on init") // printed on console
    this.subscription=this.adminService.startedEditingItem.subscribe(
      (id:string)=>{
        console.log("edit item>"+id); // not printed on console.so value is not received
        this.initForm();});
    this.initForm();}
DeborahK
  • 57,520
  • 12
  • 104
  • 129
user2800089
  • 2,015
  • 6
  • 26
  • 47

1 Answers1

0

Do you really need a Subject here? You may be able to more easily communicate using a simple service without using Subject. For example:

import { Injectable } from '@angular/core';

@Injectable() 
export class DataService {
  serviceData: string; 
}

You can find more details here: https://blogs.msmvps.com/deborahk/build-a-simple-angular-service-to-share-data/

And a plunker here:

https://plnkr.co/edit/KT4JLmpcwGBM2xdZQeI9?p=preview

DeborahK
  • 57,520
  • 12
  • 104
  • 129
  • yes your solution worked.Thanks alot.But then again I have a question why Subject are introduced if same thing can be achieved through getter/setter. I am new to angular so I would like to understand the pros and cons of both the approaches. – user2800089 Aug 09 '17 at 17:59
  • `Subject` is not an Angular thing, it is an RxJS thing (Reactive Extensions). You only need them for more complex cases where you are building your own pub/sub model. You don't need it when using Angular's already existing features, such as its change detection. Here is a blog post that covers some of the details: https://stackoverflow.com/questions/34849873/what-are-the-semantics-of-different-rxjs-subjects/34860777#34860777 – DeborahK Aug 09 '17 at 18:08