paint-brush
3 Ways to Pass Async Data to Angular + Child Componentsby@jecelynyeen
1,666 reads
1,666 reads

3 Ways to Pass Async Data to Angular + Child Components

by Jecelyn YeenJanuary 6th, 2017
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Let’ say you have a <strong>blogger </strong><a href="https://hackernoon.com/tagged/component" target="_blank"><strong>component</strong></a> that will display blogger details and her posts. Blogger component will gets the list of posts from API.
featured image - 3 Ways to Pass Async Data to Angular + Child Components
Jecelyn Yeen HackerNoon profile picture

For Angularjs or Angular 1.x posts, it will be stated 1.x explicitly, else it’s always the latest version of Angular.

Use Case

Let’ say you have a blogger component that will display blogger details and her posts. Blogger component will gets the list of posts from API.

Instead of writing the logic of displaying the posts in the blogger component, you want to reuse the posts component that is created by your teammate, what you need to do is pass it the posts data.

The posts component will then group the posts by category and display accordingly, like this:

blogger component

Isn’t That Easy?

It might look easy at the first glance. Most of the time we will initiate all the process during our component initialization time — during ngOnInit life cycle hook (refer here for more details on component life cycle hook).

In our case, you might think that we should run the post grouping logic during ngOnInit of the posts component.

However, because the posts data is coming from server, when the blogger component passes the posts data to posts component, the posts component ngOnInit is already fired before the data get updated. Your post grouping logic will not be fired.

How can we solve this? Please read further in my Scotch post.


3 Ways to Pass Async Data to Angular 2+ Child Components_Let's start with a common use case. You have some data you get from external source (e.g. by calling API). You want to…_scotch.io