简体   繁体   中英

how to subscribe for values in dynamic form of angular 2

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();}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM