An open API service indexing awesome lists of open source software.

https://github.com/overlineink/http-chapter

Consuming HTTP services and making a reusable data service for HTTPs classes
https://github.com/overlineink/http-chapter

angular best-practices http separation-of-concerns typescript

Last synced: 6 months ago
JSON representation

Consuming HTTP services and making a reusable data service for HTTPs classes

Awesome Lists containing this project

README

          

# 📖 Chapter 9 - Consuming HTTP Services

This project is part of the Angular Series Program, in this episode we present the readjustments of [Angular](https://angular.io) version 7.0.3.

We also present good practices when consuming HTTP services, we also had a brief consideration of the handling of errors for HTTP services (unexpected errors, global errors and specific errors) and to create a reusable service following the Clean Code Guides * Separation of concepts.

# Quick Start 🚀

#### Example: Posts Page

* Clone this repo

git clone https://github.com/overlineink/http-chapter.git

* Open this project on your favorite editor or IDE. For this example I was using [vscode](https://code.visualstudio.com/) a powerfull editor.

code . 

Install dependencies

 npm install 

⚠ Note: Open your command line inside the folder of your project before installing the dependencies
⚠ Advice: Generate your own services and use 'em with DataService class.

Generating `Posts` Service

ng generate service services/post
or use that for short
ng g s services/post

* Extends `DataService` class and passing expected params.


import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { DataService } from '../data.service';

@Injectable({
providedIn: 'root'
})

export class PostsService extends DataService {

constructor(http : Http) {
super('https://jsonplaceholder.typicode.com/comments', http);
}

}

* Generate `Posts` component

ng g c components/post

* Consuming our `Posts` service


import { Component, OnInit } from '@angular/core';
import { PostsService } from 'src/app/services/posts/posts.service';

@Component({
selector: 'app-posts',
templateUrl: './posts.component.html',
styleUrls: ['./posts.component.css']
})
export class PostsComponent implements OnInit {

// public helper to store posts data
posts = [];

constructor(private service: PostsService) { }

//...

ngOnInit() {
this.service.getAll()
.subscribe(posts => this.posts = posts);
}

}

* Adding posts to our `Posts` template
In this example I use Bootstrap css classes to make our app friendly.

```



{{ post.email }}

{{ post.body }}


```

* Serve your project and enjoy 🐱‍👓

 ng serve --open