0

I am trying to create a "item-list" component to host a form that receives some data as input and send a http request to server, when receiving the response I would like to broadcast the new info to the parent that should work as a "list-component".

Those are my entities:

export class Parent {
    children: Array<Child>;
}

export class Child { ... }

The service layer is returning the full parent entity for every request, we know this is not the best aproach, but that is another problem.

The component is actually working like that:

export class ListItemComponent {

    ...

    @Input()
    parent: Parent;

    private output: EventEmmiter<Parent> = new EventEmmiter<Parent>();

    submit() {
        service.post(this.item).subscribe(
            data => {
                this.parent = data;
                this.output.emit(this.parent);
            }
        );
    }
}

Everything works normal except that the ListComponent don't render the new Child, in my tests I tried to add a new instance of Child outside the subscribe() method and call output.emit() and that actually worked well, so I am guessing that the problem is somehow related to calling output.emit() inside subscribe().

Any help is welcome!

Victor Carvalho
  • 1,610
  • 3
  • 14
  • 18

1 Answers1

1

You can try running this.output.emit(this.parent); in Angular Zone:

export class ListItemComponent {

  ...

  @Input()
  parent: Parent;

  private output: EventEmmiter<Parent> = new EventEmmiter<Parent>();

  constructor(private ngZone: NgZone) {}

  submit() {
      service.post(this.item).subscribe(
          data => {
              this.parent = data;
              this.ngZone.run(() => this.output.emit(this.parent));
          }
      );
  }

}

A bit documentation about NgZone: https://angular.io/docs/ts/latest/api/core/index/NgZone-class.html#!#run-anchor

You can find issue about that here: https://github.com/angular/zone.js/issues/304

kruczjak
  • 141
  • 2