Using promises to create asynchronous services in Angular
In the preceding section, our current user data was essentially synchronous, so there wasn't an opportunity to observe any asynchronous behavior between the service and component. Services can be very useful for resolving asynchronous dependencies in Angular through the use of promises.
Getting ready
Let's create a BlogPostsService
to retrieve our blog posts. We will set this service up as an asynchronous promise that will resolve when it has loaded our posts. We will mock the blog post results for now, but will set it up so that we can eventually swap out with the internals to use an API request instead.
Before we get started, we'll once again scaffold out our content using Angular-CLI's generate command. We will need a new BlogPostsService
, as well as as a new PostListComponent
to display all our blog posts to the user:
ng generate service posts/blog-posts ng generate component posts/post-list
How to do it...
Let's carry out the following...