Search code examples
angulartypescriptroutesangular-components

Angular: simplest way to visually handle api-request-errors from child-component in parent-component (parent uses router or dynamic components)


Let's say I have a parent element with router-outlet that routs to children-components. Like in the first 10 seconds of the fireship youtube tutorial: https://youtu.be/Np3ULAMqwNo

I have 10 different but similar child-components. The child component will do some API-requests. How can the parent-component display what went wrong in the API request? I don't want to write the same error-display code 10 times. Should I define some different error-codes and pass them up somehow?

Is it smart to use a router in that case even? What are the alternatives? Make requests in parent and send to child? But then how do I pass a complex response down the router-outlet?

Or can you create a generic "interface" component like in JAVA which has the error-handling and then specify the rest in the implementation of that component? If someone could point me to the right "construct" to do that, please. I researched a bit and found nothing.

I just want to prevent 10x repeated code to show the error in the children.

edit: I am also considering to use ngSwitchCase in parent to select the child-components instead of using routing. Is this maybe the best way to do it here? Binding lots of data between parent/child wouldn't be a problem here, you could probably communicate errors from the child component to the parent component. But how, with what "CONSTRUCT" would this be done the best?


Solution

  • You could do the requests in the parent component.

    Then, you can pass information through routing. Normally, you would use route parameters for this. But for complex objects which you don't want to display in your URL you can do something like this:

    this.router.navigate(["childComponentPath"], { state: { data: <response> }});
    

    and then in your child component you can retrieve the data like this:

    this.data = this.router.getCurrentNavigation().extras.state["data"]
    

    UPDATE:

    So while creating a StackBlitz demo for this solution, I found there is a tiny problem if you refresh the page. Because the data are passed on navigation, if you refresh the page you lose the data.

    So you will either have to redirect back to the "home" route (already implemented in StackBlitz), or use a different solution altogether.

    As an alternative, you could make the requests in your child components and communicate the error with a service to your parent component.