0

I called one method from child.

In child component:

@Output() parentEvent = new EventEmitter<any>();

click1() {
    //calling the method from child
    this.parentEvent.emit(myObj1);    
}

In parent component:

postMethod1(event) {
    //calling one post method(observable)
}

I need to call this postMethod1() method from child component. But the problem is that if any exception thrown in parent how can I handle this in child component? Cannot get the response from parent to child. How can I handle this?

Roland Rácz
  • 2,879
  • 3
  • 18
  • 44
vik
  • 105
  • 13

2 Answers2

1

To listen to the eventEmitted , all you have to do is :

<child-component (parentEvent)='postMethod1($event)'></child-component>

Now everytime an event is emitted by child component , postMethod1() is called and the data sent will be passed as parameter to the method .

EDIT

Since you want to handle the exception , you can use a shared service to notify the child component .

Suppose you have a shared.service.ts

In shared.service.ts ,you can do something like this :

exception : Subject<String> = new Subject<String>();

now you can create a method to send an exception from parent to child :

exceptionRaised(parentException : any){
 this.exception.next(parentException);
}

With this method , the exception can be subscribed in the child component like this :

in child.component.ts

_sharedService.exception.subscribe((exception : any) =>{
  //do whatever you want with the exception
});

To set the exception in parent , in parent.component.ts just call _sharedService.exceptionRaised(yourException);

Now your parent can communicate with child and notify if you have an exception

CruelEngine
  • 2,701
  • 4
  • 23
  • 44
1

Say your child has the tag app-child. Then the correct syntax is :

<app-child (parentEvent)="postMethod1($event)"></app-child>

EDIT For your second issue, use a ViewChild in your parent component :

export class ParentComponent {
  @ViewChild(ChildComponent) child: ChildComponent;

  // Rest of your code

  postMethod1(event: any) {
    this.myService.makeHttpPost().subscribe(response => null, error => {
      this.child.handleError(error);
    });
  }
}

This will call the handleError in your child component.

  • Event is getting called. Problem is once this method called from child i need to write another post call in child component. If anything failed in postMethod1() method. Another post call must stopped. – vik Mar 12 '18 at 11:23