Javascript News - A collection of audio articles aimed toward Full Stack Development with JS.

Angular 2 - Mastering Google's Front-End Framework - Chapter 4 - Using Services In Angular


Listen Later

When using the Http Client Module: it is common to have a Services folder and subsequent files in order to keep track of the http request and responses to and from the backend. To generate a service in Angular I am going to use the Angular CLI.

ng generate service services/http

This will generate a new http.service.ts file in our myBlog/src/app/services folder. It should be green if you are using VS Code. If one is on a Mac they can allow VS Code (a Microsoft Product) to edit the file with the following command. This is not necessary if you are a Windows or Linux machine. This following command is to be run in the root of the myBlog directory.

sudo chown -R myBlog/app/src/services

Next we are going to migrate our Http Client Module code from the app.component.ts file to the services/http.service.ts file. This will look like so when finished.

import { Injectable } from '@angular/core';

import { HttpClient } from '@angular/common/http';

@Injectable({

providedIn: 'root'

})

export class HttpService {

constructor(private http: HttpClient) { }

getBlogPosts() {

return this.http.get('/api/blogPosts');

}

}

The service can then be imported into the app.component.ts file like so. First import the service module that was just created.

import { HttpService } from './services/http.service';

Then one can use the constructor to add the service into the project.

constructor(private service: HttpService) { }

Then one can use the method that was just built to get the Blog Posts.

ngOnInit() {

this.service.getBlogPosts().subscribe((res: any) => {

if (res) {

this.blogPosts = res['posts'];

}

})

}

This completes the introduction to Angular Services. They can be used to clean up the structure of your application and make it easier to do Http Requests with Angular. Now in the browser one would see this: depending on the content of their backend server’s data.

---
This episode is sponsored by
· Anchor: The easiest way to make a podcast. https://anchor.fm/app
---
Send in a voice message: https://anchor.fm/javascript-news/message
Support this podcast: https://anchor.fm/javascript-news/support
...more
View all episodesView all episodes
Download on the App Store

Javascript News - A collection of audio articles aimed toward Full Stack Development with JS.By Javascript News