(Go: >> BACK << -|- >> HOME <<)

SlideShare a Scribd company logo
www.webstackacademy.com
HTTP Services
Angular
www.webstackacademy.comwww.webstackacademy.com
HTTP Services
(Accessing services from the web)
www.webstackacademy.com
Introduction to HTTP
• Hyper Text Transfer Protocol (HTTP) is the client-server network protocol that has been in use by
the World Wide Web (WWW) since 1990.
• HTTP protocol is defined in RFC 7230 as per IETF standardization
• It is one of the application layer protocols in the TCP/IP suite of protocols.
• Whenever you are browsing the web, your browser will be sending HTTP request messages for various
Resources (HTML pages, images etc..) and fetch them from the server
www.webstackacademy.com
Introduction to HTTP
• Web servers handle these requests as a HTTP server by returning response messages that contain the
requested resource. The client "pulls" the data from the server rather than the server "push"
• HTTP is a Stateless protocol. This means the current request does not know what has been done in the
previous requests.
• HTTP permits negotiating of data type and representation, so as to allow systems to be built independently
of the data being transferred.
• In summary we can say HTTP is a application-level protocol for distributed, collaborative, hypermedia
information systems.
www.webstackacademy.com
HTTP methods
HTTP supports a set of methods, out of which four are very important and frequently used.
Method Description
GET The GET method is used to retrieve information from the given server using a given URI.
DELETE Removes all current representations of the target resource given by a URI
PUT Replaces all current representations of the target resource with the uploaded content
POST A POST request is sent by the client to the server with all the data collected in the client end
www.webstackacademy.com
HTTP response code
Upon receiving HTTP request, the server provides appropriate responses. They are categorized as follows:
Code Category Description
1XX Informational Request received, server is continuing the process.
2XX Success The request was successfully received, understood, accepted and
serviced.
3XX Redirection Further action must be taken in order to complete the request.
4XX Client Error The request contains bad syntax or cannot be understood.
5XX Server Error The server failed to fulfil an apparently valid request.
www.webstackacademy.com
HTTP response code - Examples
Code Category Description
100 Continue The server received the request and in the process of giving the response.
200 OK The request is fulfilled.
301 Resource moved The client should issue a new request to the new location.
400 Bad Request Server could not interpret or understand the request, probably syntax error in the request
message.
401 Authentication
Required
The requested resource is protected, and require client’s credential (username/password).
403 Forbidden Server refuses to supply the resource, regardless of identity of client.
404 Not Found The requested resource cannot be found in the server.
500 Internal Server
Error
Server is confused, often caused by an error in the server-side program responding to the
request.
501 Method Not
Implemented
The request method used is invalid
www.webstackacademy.comwww.webstackacademy.com
REST Interfaces
(Web services with REST)
www.webstackacademy.com
REST Interfaces
• REST stands for REpresentational State
Transfer.
• REST is a web standards based architecture
and that uses HTTP as the underlying
protocol for communication.
• It has a notion of "resource" where
everything revolves around that. The
resource is accessed by a common
interface using HTTP standard methods.
• REST was first introduced by Roy Fielding in
year 2000.
www.webstackacademy.com
RESTful Web Services
• A web service is a collection of open protocols and standards used for exchanging data between
applications over the internet.
• Web services based on REST Architecture are known as RESTful Web Services. These web
services use HTTP methods to implement the concept of REST architecture.
• Since HTTP offers two way communication methods, RESTful web service added a layer on top
of it to implement meaningful web services using URI.
www.webstackacademy.com
Characteristics of REST
• Three characteristics of REST:
 Stateless: Client data is not stored on the server between interactions and the session is
stored client-side (typically in session storage).
 Client <-> Server: There is a “separation of concerns” between the frontend (client) and the
backend (server). They operate independently of each other and both are replaceable.
 Cache: Data from the server can be cached on the client, which can improve performance
speed.
• In addition to these three fundamental features of REST, there is also a uniform approach to the
composition of URLs. This allows for a standardization of service, which prior to the introduction
of REST, did not exist.
www.webstackacademy.com
Characteristics of REST
• For example, a GET request to /courses, should yield all the courses in the database, whereas
a GET request to /courses/20 would render the course with ID of 20.
• Similarly, REST utilizes standard methods like GET, PUT, DELETE and POST to perform actions.
• Today every major web service provider expose RESTful interfaces (called as REST APIs) using
which client applications can enable client application developers develop application with ease
www.webstackacademy.com
A Brief about JSON
• JSON: JavaScript Object Notation.
• It is a lightweight data-interchange format, easy for humans to read and write.
• All programming languages support them, easy to parse and interpret
• One of the common standards used in data exchange for client-server communication.
Servers as an alternative option for other data representations (ex: XML)
• Data is represented as name-value pairs and array data types.
www.webstackacademy.com
JSON - Example
{
"firstName": “WebStack",
"lastName“ : “Academy",
“domain“ : “Education”,
"phoneNumber": [
{
"type": “landline",
"number": “91-80-41289576"
},
{
"type": “mobile",
"number": “8095557334"
}
],
}
www.webstackacademy.comwww.webstackacademy.com
HTTP services in Angular
(Practical implementing in Angular)
www.webstackacademy.com
Make the Angular and related import paths
import { HttpModule } from '@angular/http';
@NgModule({
declarations: [
AppComponent,
HttpComponent,
],
imports: [
BrowserModule,
HttpModule // Import HTTP module here
],
providers: [
EndPointServiceService
],
})
1. Import HTTP into app.module.ts
www.webstackacademy.com
2. Accessing HTTP
Access your HTTP service via constructor and access methods
myPosts: any[];
private myURL = 'http://jsonplaceholder.typicode.com/posts';
constructor(private myHttp: Http) {
// By default populate all posts....
myHttp.get(this.myURL).subscribe(response => {
console.log(response.json());
this.myPosts = response.json();
});
}
www.webstackacademy.com
HTTP methods in Angular
Here are the HTTP method details in Angular
Method Definition
GET get(url: string, options?: RequestOptionsArgs):
Observable<Response>
DELETE delete(url: string, options?: RequestOptionsArgs):
Observable<Response>
PUT put(url: string, body: any, options?: RequestOptionsArgs):
Observable<Response>
POST post(url: string, body: any, options?: RequestOptionsArgs):
Observable<Response>
• NOTE: All functions return Observarable, you need to subscribe to get actual return values / error codes
• Response type has got multiple fields, which can be obtained from Angular official documentation
(https://angular.io/api/http/Response)
www.webstackacademy.comwww.webstackacademy.com
Separation of Concerns
(Delegating HTTP handling to services)
www.webstackacademy.com
Separation of Concern (SoC) - Concept
• In computer science, separation of concerns (SoC) is a
design principle for separating a computer program into
distinct sections, such that each section addresses a
separate concern.
• A concern is a set of information that affects the code of
a computer program (Functionality).
• It is always a good practise to implement SoC well in
your program, so that is becomes modular.
• By making it modular we get other benefits in terms of
re-usability, maintainability and simplifies development
process.
www.webstackacademy.com
Separation of Concern (SoC) - Implementation
• Practically it is achieved by encapsulating information
inside a section of code that has a well-defined
interface.
• The section of code which is interested, will invoke this
interface and obtain required information
• This is also called as data encapsulation is a means of
information hiding. The calling section will not know the
detail orientation but only concerned about its objective
• Typically these interfaces are methods / APIs and
implemented via various OOP mechanisms – Classes,
Constructors etc..
• In Angular also we have used these concepts already!
www.webstackacademy.com
Separation of Concern (SoC) in Angular
www.webstackacademy.com
Separation of Concern (SoC) in Angular
• In Angular, we have seen separation of concern happening at component level as follows:
 Template - HTML file
 Style - CSS file
 Business Logic - TS file
• The main goal of the component is to deal with business logic related to view (Template + Style)
• When it comes to dealing with HTTP services (ex: Fetching course list from Firebase) it should
NOT be done as a part of component to adhere to SoC
• The idea is to implement a service and access them via a method. This way you are “delegating"
the action to a service. In this process you also achieve benefits of SoC.
www.webstackacademy.com
Separation of Concern (SoC) in Angular - Problem
export class HttpComponent implements OnInit {
myPosts: any[];
private myURL = 'http://jsonplaceholder.typicode.com/posts';
// Method for creating a new post
createNewPost(userTitle: HTMLInputElement) {
let newPost = { title: userTitle.value };
this.myHttp.post(this.myURL,JSON.stringify(newPost)).subscribe(
response => {
console.log(response.json());
this.myPosts.splice(0,0,newPost);
});
}
www.webstackacademy.com
Separation of Concern (SoC) in Angular - Solution
export class NewHttpComponentComponent implements OnInit {
myPosts: any[];
constructor(private service: EndPointServiceService) {
}
createNewPost(userTitle: HTMLInputElement) {
let newPost = { title: userTitle.value };
this.service.createPost(newPost).subscribe (
response => {
this.myPosts.splice(0,0,newPost);
});
}
www.webstackacademy.comwww.webstackacademy.com
Error handling in HTTP
(Expected & Unexpected Errors)
www.webstackacademy.com
HTTP Errors
• During the HTTP communication there could be many errors that could be happening
• The application should capture errors and handle them appropriately
HTTP Errors
Unexpected Errors Expected Errors
• Offline Server
• N/W down
• API Error
• …….
• Not found (404)
• Bad request (400)
• Auth Failure (401)
• …….
www.webstackacademy.com
HTTP Errors – Handling in Angular
deleteExistingPost (dPost){
this.service.deletePost(dPost).subscribe (
response => {
console.log("Post deleted successfully");
let dPostIndex = this.myPosts.indexOf(dPost);
this.myPosts.splice(dPostIndex,1); },
error => {
if (error.status == 404) // Expected Error
alert ("Post already deleted");
else { // Unexpected Error
alert ("An unexpected error occurred");
console.log(error);
}
});
}
www.webstackacademy.comwww.webstackacademy.com
Building re-usable services
(HTTP methods remain similar!)
www.webstackacademy.com
Building re-usable services
• In HTTP based services, the common operations remain the same
• In such cases each service may not want to implement the same methods. In order to achieve
that services can be made re-usable using inheritance
Step-1: Create a new TS file (ex: generic.service.ts) and import all HTTP methods into it
export class GenericService {
constructor(myURL: string, myHttp : Http) {
}
getPosts() { … }
createPost(userPost) { … }
updatePost(userPost) { … }
deletePost(userPost) { … }
}
}
www.webstackacademy.com
Building re-usable services
Step-2: From the service’s main class, inherit this class. Also use constructor of the parent to
pass parameters and initialization.
export class EndPointServiceService extends GenericService {
}
super(myURL, myHttp);
www.webstackacademy.com
Exercise
• Create a GITHub followers page by accessing REST API provided by the GIT
• Example URL: https://api.github.com/users/devendradora/followers
www.webstackacademy.com
Exercise
• Ensure you apply following learnings:
 New component to handle the main business logic
 New re-usable service interacting with REST API
 HTTP error handling
 Directives for rendering all followers
 CSS changes to display the follower names in a user friendly way
 Display the following attributes:
 Avatar (Profile picture)
 GIT profile URL
 Login name
www.webstackacademy.com
WebStack Academy
#83, Farah Towers,
1st Floor, MG Road,
Bangalore – 560001
M: +91-809 555 7332
E: training@webstackacademy.com
WSA in Social Media:

More Related Content

What's hot

Angular introduction students
Angular introduction studentsAngular introduction students
Angular introduction students
Christian John Felix
 
Angular Data Binding
Angular Data BindingAngular Data Binding
Angular Data Binding
Jennifer Estrada
 
Angular
AngularAngular
Angular - Chapter 3 - Components
Angular - Chapter 3 - ComponentsAngular - Chapter 3 - Components
Angular - Chapter 3 - Components
WebStackAcademy
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 forms
Eyal Vardi
 
Angular 5 presentation for beginners
Angular 5 presentation for beginnersAngular 5 presentation for beginners
Angular 5 presentation for beginners
Imran Qasim
 
Introduction to angular with a simple but complete project
Introduction to angular with a simple but complete projectIntroduction to angular with a simple but complete project
Introduction to angular with a simple but complete project
Jadson Santos
 
Angular
AngularAngular
Angular Observables & RxJS Introduction
Angular Observables & RxJS IntroductionAngular Observables & RxJS Introduction
Angular Observables & RxJS Introduction
Rahat Khanna a.k.a mAppMechanic
 
Angular Dependency Injection
Angular Dependency InjectionAngular Dependency Injection
Angular Dependency Injection
Nir Kaufman
 
Angular modules in depth
Angular modules in depthAngular modules in depth
Angular modules in depth
Christoffer Noring
 
AngularJS
AngularJS AngularJS
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
Edureka!
 
Angular Directives
Angular DirectivesAngular Directives
Angular Directives
iFour Technolab Pvt. Ltd.
 
Angular Basics.pptx
Angular Basics.pptxAngular Basics.pptx
Angular Basics.pptx
AshokKumar616995
 
Introduzione ad angular 7/8
Introduzione ad angular 7/8Introduzione ad angular 7/8
Introduzione ad angular 7/8
Valerio Radice
 
Angular Data Binding
Angular Data BindingAngular Data Binding
Angular Data Binding
Duy Khanh
 
Angular directives and pipes
Angular directives and pipesAngular directives and pipes
Angular directives and pipes
Knoldus Inc.
 
Angular tutorial
Angular tutorialAngular tutorial
Angular tutorial
Rohit Gupta
 
Angular 6 - The Complete Guide
Angular 6 - The Complete GuideAngular 6 - The Complete Guide
Angular 6 - The Complete Guide
Sam Dias
 

What's hot (20)

Angular introduction students
Angular introduction studentsAngular introduction students
Angular introduction students
 
Angular Data Binding
Angular Data BindingAngular Data Binding
Angular Data Binding
 
Angular
AngularAngular
Angular
 
Angular - Chapter 3 - Components
Angular - Chapter 3 - ComponentsAngular - Chapter 3 - Components
Angular - Chapter 3 - Components
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 forms
 
Angular 5 presentation for beginners
Angular 5 presentation for beginnersAngular 5 presentation for beginners
Angular 5 presentation for beginners
 
Introduction to angular with a simple but complete project
Introduction to angular with a simple but complete projectIntroduction to angular with a simple but complete project
Introduction to angular with a simple but complete project
 
Angular
AngularAngular
Angular
 
Angular Observables & RxJS Introduction
Angular Observables & RxJS IntroductionAngular Observables & RxJS Introduction
Angular Observables & RxJS Introduction
 
Angular Dependency Injection
Angular Dependency InjectionAngular Dependency Injection
Angular Dependency Injection
 
Angular modules in depth
Angular modules in depthAngular modules in depth
Angular modules in depth
 
AngularJS
AngularJS AngularJS
AngularJS
 
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
 
Angular Directives
Angular DirectivesAngular Directives
Angular Directives
 
Angular Basics.pptx
Angular Basics.pptxAngular Basics.pptx
Angular Basics.pptx
 
Introduzione ad angular 7/8
Introduzione ad angular 7/8Introduzione ad angular 7/8
Introduzione ad angular 7/8
 
Angular Data Binding
Angular Data BindingAngular Data Binding
Angular Data Binding
 
Angular directives and pipes
Angular directives and pipesAngular directives and pipes
Angular directives and pipes
 
Angular tutorial
Angular tutorialAngular tutorial
Angular tutorial
 
Angular 6 - The Complete Guide
Angular 6 - The Complete GuideAngular 6 - The Complete Guide
Angular 6 - The Complete Guide
 

Similar to Angular - Chapter 7 - HTTP Services

Ch-1_.ppt
Ch-1_.pptCh-1_.ppt
Ch-1_.ppt
berihunmolla2
 
0_Leksion_Web_Servers (1).pdf
0_Leksion_Web_Servers (1).pdf0_Leksion_Web_Servers (1).pdf
0_Leksion_Web_Servers (1).pdf
Zani10
 
Restful web services
Restful web servicesRestful web services
Restful web services
MD Sayem Ahmed
 
Rest WebAPI with OData
Rest WebAPI with ODataRest WebAPI with OData
Rest WebAPI with OData
Mahek Merchant
 
SCWCD : The web client model
SCWCD : The web client modelSCWCD : The web client model
SCWCD : The web client model
Ben Abdallah Helmi
 
SCWCD : The web client model : CHAP : 1
SCWCD  : The web client model : CHAP : 1SCWCD  : The web client model : CHAP : 1
SCWCD : The web client model : CHAP : 1
Ben Abdallah Helmi
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
WebStackAcademy
 
web-servers3952 (1)qwjelkjqwlkjkqlwe.ppt
web-servers3952 (1)qwjelkjqwlkjkqlwe.pptweb-servers3952 (1)qwjelkjqwlkjkqlwe.ppt
web-servers3952 (1)qwjelkjqwlkjkqlwe.ppt
20521742
 
Html intake 38 lect1
Html intake 38 lect1Html intake 38 lect1
Html intake 38 lect1
ghkadous
 
Web Technologies Notes - TutorialsDuniya.pdf
Web Technologies Notes - TutorialsDuniya.pdfWeb Technologies Notes - TutorialsDuniya.pdf
Web Technologies Notes - TutorialsDuniya.pdf
Raghunathan52
 
Web Technologies Notes - TutorialsDuniya.pdf
Web Technologies Notes - TutorialsDuniya.pdfWeb Technologies Notes - TutorialsDuniya.pdf
Web Technologies Notes - TutorialsDuniya.pdf
Raghunathan52
 
Introduction to Web Architecture
Introduction to Web ArchitectureIntroduction to Web Architecture
Introduction to Web Architecture
Chamnap Chhorn
 
ASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiASP.NET Mvc 4 web api
ASP.NET Mvc 4 web api
Tiago Knoch
 
Mini-Training: Let's have a rest
Mini-Training: Let's have a restMini-Training: Let's have a rest
Mini-Training: Let's have a rest
Betclic Everest Group Tech Team
 
Advanced Web Design And Development BIT 3207
Advanced Web Design And Development BIT 3207Advanced Web Design And Development BIT 3207
Advanced Web Design And Development BIT 3207
Lori Head
 
SharePoint 2013 - What's New
SharePoint 2013 - What's NewSharePoint 2013 - What's New
SharePoint 2013 - What's New
AdventosConsulting
 
REST API Recommendations
REST API RecommendationsREST API Recommendations
REST API Recommendations
Jeelani Shaik
 
Restful webservices
Restful webservicesRestful webservices
Restful webservices
Luqman Shareef
 
REST & RESTful Web Services
REST & RESTful Web ServicesREST & RESTful Web Services
REST & RESTful Web Services
Halil Burak Cetinkaya
 
Api design and development
Api design and developmentApi design and development
Api design and development
oquidave
 

Similar to Angular - Chapter 7 - HTTP Services (20)

Ch-1_.ppt
Ch-1_.pptCh-1_.ppt
Ch-1_.ppt
 
0_Leksion_Web_Servers (1).pdf
0_Leksion_Web_Servers (1).pdf0_Leksion_Web_Servers (1).pdf
0_Leksion_Web_Servers (1).pdf
 
Restful web services
Restful web servicesRestful web services
Restful web services
 
Rest WebAPI with OData
Rest WebAPI with ODataRest WebAPI with OData
Rest WebAPI with OData
 
SCWCD : The web client model
SCWCD : The web client modelSCWCD : The web client model
SCWCD : The web client model
 
SCWCD : The web client model : CHAP : 1
SCWCD  : The web client model : CHAP : 1SCWCD  : The web client model : CHAP : 1
SCWCD : The web client model : CHAP : 1
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 
web-servers3952 (1)qwjelkjqwlkjkqlwe.ppt
web-servers3952 (1)qwjelkjqwlkjkqlwe.pptweb-servers3952 (1)qwjelkjqwlkjkqlwe.ppt
web-servers3952 (1)qwjelkjqwlkjkqlwe.ppt
 
Html intake 38 lect1
Html intake 38 lect1Html intake 38 lect1
Html intake 38 lect1
 
Web Technologies Notes - TutorialsDuniya.pdf
Web Technologies Notes - TutorialsDuniya.pdfWeb Technologies Notes - TutorialsDuniya.pdf
Web Technologies Notes - TutorialsDuniya.pdf
 
Web Technologies Notes - TutorialsDuniya.pdf
Web Technologies Notes - TutorialsDuniya.pdfWeb Technologies Notes - TutorialsDuniya.pdf
Web Technologies Notes - TutorialsDuniya.pdf
 
Introduction to Web Architecture
Introduction to Web ArchitectureIntroduction to Web Architecture
Introduction to Web Architecture
 
ASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiASP.NET Mvc 4 web api
ASP.NET Mvc 4 web api
 
Mini-Training: Let's have a rest
Mini-Training: Let's have a restMini-Training: Let's have a rest
Mini-Training: Let's have a rest
 
Advanced Web Design And Development BIT 3207
Advanced Web Design And Development BIT 3207Advanced Web Design And Development BIT 3207
Advanced Web Design And Development BIT 3207
 
SharePoint 2013 - What's New
SharePoint 2013 - What's NewSharePoint 2013 - What's New
SharePoint 2013 - What's New
 
REST API Recommendations
REST API RecommendationsREST API Recommendations
REST API Recommendations
 
Restful webservices
Restful webservicesRestful webservices
Restful webservices
 
REST & RESTful Web Services
REST & RESTful Web ServicesREST & RESTful Web Services
REST & RESTful Web Services
 
Api design and development
Api design and developmentApi design and development
Api design and development
 

More from WebStackAcademy

Webstack Academy - Course Demo Webinar and Placement Journey
Webstack Academy - Course Demo Webinar and Placement JourneyWebstack Academy - Course Demo Webinar and Placement Journey
Webstack Academy - Course Demo Webinar and Placement Journey
WebStackAcademy
 
WSA: Scaling Web Service to Handle Millions of Requests per Second
WSA: Scaling Web Service to Handle Millions of Requests per SecondWSA: Scaling Web Service to Handle Millions of Requests per Second
WSA: Scaling Web Service to Handle Millions of Requests per Second
WebStackAcademy
 
WSA: Course Demo Webinar - Full Stack Developer Course
WSA: Course Demo Webinar - Full Stack Developer CourseWSA: Course Demo Webinar - Full Stack Developer Course
WSA: Course Demo Webinar - Full Stack Developer Course
WebStackAcademy
 
Career Building in AI - Technologies, Trends and Opportunities
Career Building in AI - Technologies, Trends and OpportunitiesCareer Building in AI - Technologies, Trends and Opportunities
Career Building in AI - Technologies, Trends and Opportunities
WebStackAcademy
 
Webstack Academy - Internship Kick Off
Webstack Academy - Internship Kick OffWebstack Academy - Internship Kick Off
Webstack Academy - Internship Kick Off
WebStackAcademy
 
Building Your Online Portfolio
Building Your Online PortfolioBuilding Your Online Portfolio
Building Your Online Portfolio
WebStackAcademy
 
Front-End Developer's Career Roadmap
Front-End Developer's Career RoadmapFront-End Developer's Career Roadmap
Front-End Developer's Career Roadmap
WebStackAcademy
 
Angular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and AuthorizationAngular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and Authorization
WebStackAcademy
 
Angular - Chapter 6 - Firebase Integration
Angular - Chapter 6 - Firebase IntegrationAngular - Chapter 6 - Firebase Integration
Angular - Chapter 6 - Firebase Integration
WebStackAcademy
 
Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming  Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming
WebStackAcademy
 
JavaScript - Chapter 10 - Strings and Arrays
 JavaScript - Chapter 10 - Strings and Arrays JavaScript - Chapter 10 - Strings and Arrays
JavaScript - Chapter 10 - Strings and Arrays
WebStackAcademy
 
JavaScript - Chapter 15 - Debugging Techniques
 JavaScript - Chapter 15 - Debugging Techniques JavaScript - Chapter 15 - Debugging Techniques
JavaScript - Chapter 15 - Debugging Techniques
WebStackAcademy
 
JavaScript - Chapter 14 - Form Handling
 JavaScript - Chapter 14 - Form Handling   JavaScript - Chapter 14 - Form Handling
JavaScript - Chapter 14 - Form Handling
WebStackAcademy
 
JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)
WebStackAcademy
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events
WebStackAcademy
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
WebStackAcademy
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - Objects
WebStackAcademy
 
JavaScript - Chapter 7 - Advanced Functions
 JavaScript - Chapter 7 - Advanced Functions JavaScript - Chapter 7 - Advanced Functions
JavaScript - Chapter 7 - Advanced Functions
WebStackAcademy
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic Functions
WebStackAcademy
 

More from WebStackAcademy (20)

Webstack Academy - Course Demo Webinar and Placement Journey
Webstack Academy - Course Demo Webinar and Placement JourneyWebstack Academy - Course Demo Webinar and Placement Journey
Webstack Academy - Course Demo Webinar and Placement Journey
 
WSA: Scaling Web Service to Handle Millions of Requests per Second
WSA: Scaling Web Service to Handle Millions of Requests per SecondWSA: Scaling Web Service to Handle Millions of Requests per Second
WSA: Scaling Web Service to Handle Millions of Requests per Second
 
WSA: Course Demo Webinar - Full Stack Developer Course
WSA: Course Demo Webinar - Full Stack Developer CourseWSA: Course Demo Webinar - Full Stack Developer Course
WSA: Course Demo Webinar - Full Stack Developer Course
 
Career Building in AI - Technologies, Trends and Opportunities
Career Building in AI - Technologies, Trends and OpportunitiesCareer Building in AI - Technologies, Trends and Opportunities
Career Building in AI - Technologies, Trends and Opportunities
 
Webstack Academy - Internship Kick Off
Webstack Academy - Internship Kick OffWebstack Academy - Internship Kick Off
Webstack Academy - Internship Kick Off
 
Building Your Online Portfolio
Building Your Online PortfolioBuilding Your Online Portfolio
Building Your Online Portfolio
 
Front-End Developer's Career Roadmap
Front-End Developer's Career RoadmapFront-End Developer's Career Roadmap
Front-End Developer's Career Roadmap
 
Angular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and AuthorizationAngular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and Authorization
 
Angular - Chapter 6 - Firebase Integration
Angular - Chapter 6 - Firebase IntegrationAngular - Chapter 6 - Firebase Integration
Angular - Chapter 6 - Firebase Integration
 
Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming  Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming
 
JavaScript - Chapter 10 - Strings and Arrays
 JavaScript - Chapter 10 - Strings and Arrays JavaScript - Chapter 10 - Strings and Arrays
JavaScript - Chapter 10 - Strings and Arrays
 
JavaScript - Chapter 15 - Debugging Techniques
 JavaScript - Chapter 15 - Debugging Techniques JavaScript - Chapter 15 - Debugging Techniques
JavaScript - Chapter 15 - Debugging Techniques
 
JavaScript - Chapter 14 - Form Handling
 JavaScript - Chapter 14 - Form Handling   JavaScript - Chapter 14 - Form Handling
JavaScript - Chapter 14 - Form Handling
 
JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - Objects
 
JavaScript - Chapter 7 - Advanced Functions
 JavaScript - Chapter 7 - Advanced Functions JavaScript - Chapter 7 - Advanced Functions
JavaScript - Chapter 7 - Advanced Functions
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic Functions
 

Recently uploaded

this resume for sadika shaikh bca student
this resume for sadika shaikh bca studentthis resume for sadika shaikh bca student
this resume for sadika shaikh bca student
SadikaShaikh7
 
STKI Israeli Market Study 2024 final v1
STKI Israeli Market Study 2024 final  v1STKI Israeli Market Study 2024 final  v1
STKI Israeli Market Study 2024 final v1
Dr. Jimmy Schwarzkopf
 
MYIR Product Brochure - A Global Provider of Embedded SOMs & Solutions
MYIR Product Brochure - A Global Provider of Embedded SOMs & SolutionsMYIR Product Brochure - A Global Provider of Embedded SOMs & Solutions
MYIR Product Brochure - A Global Provider of Embedded SOMs & Solutions
Linda Zhang
 
What's Next Web Development Trends to Watch.pdf
What's Next Web Development Trends to Watch.pdfWhat's Next Web Development Trends to Watch.pdf
What's Next Web Development Trends to Watch.pdf
SeasiaInfotech2
 
The Rise of Supernetwork Data Intensive Computing
The Rise of Supernetwork Data Intensive ComputingThe Rise of Supernetwork Data Intensive Computing
The Rise of Supernetwork Data Intensive Computing
Larry Smarr
 
Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...
BookNet Canada
 
Data Protection in a Connected World: Sovereignty and Cyber Security
Data Protection in a Connected World: Sovereignty and Cyber SecurityData Protection in a Connected World: Sovereignty and Cyber Security
Data Protection in a Connected World: Sovereignty and Cyber Security
anupriti
 
Verti - EMEA Insurer Innovation Award 2024
Verti - EMEA Insurer Innovation Award 2024Verti - EMEA Insurer Innovation Award 2024
Verti - EMEA Insurer Innovation Award 2024
The Digital Insurer
 
Why do You Have to Redesign?_Redesign Challenge Day 1
Why do You Have to Redesign?_Redesign Challenge Day 1Why do You Have to Redesign?_Redesign Challenge Day 1
Why do You Have to Redesign?_Redesign Challenge Day 1
FellyciaHikmahwarani
 
Running a Go App in Kubernetes: CPU Impacts
Running a Go App in Kubernetes: CPU ImpactsRunning a Go App in Kubernetes: CPU Impacts
Running a Go App in Kubernetes: CPU Impacts
ScyllaDB
 
UiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs ConferenceUiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs Conference
UiPathCommunity
 
Performance Budgets for the Real World by Tammy Everts
Performance Budgets for the Real World by Tammy EvertsPerformance Budgets for the Real World by Tammy Everts
Performance Budgets for the Real World by Tammy Everts
ScyllaDB
 
20240702 QFM021 Machine Intelligence Reading List June 2024
20240702 QFM021 Machine Intelligence Reading List June 202420240702 QFM021 Machine Intelligence Reading List June 2024
20240702 QFM021 Machine Intelligence Reading List June 2024
Matthew Sinclair
 
How Netflix Builds High Performance Applications at Global Scale
How Netflix Builds High Performance Applications at Global ScaleHow Netflix Builds High Performance Applications at Global Scale
How Netflix Builds High Performance Applications at Global Scale
ScyllaDB
 
DealBook of Ukraine: 2024 edition
DealBook of Ukraine: 2024 editionDealBook of Ukraine: 2024 edition
DealBook of Ukraine: 2024 edition
Yevgen Sysoyev
 
Observability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetryObservability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetry
Eric D. Schabell
 
Cookies program to display the information though cookie creation
Cookies program to display the information though cookie creationCookies program to display the information though cookie creation
Cookies program to display the information though cookie creation
shanthidl1
 
Research Directions for Cross Reality Interfaces
Research Directions for Cross Reality InterfacesResearch Directions for Cross Reality Interfaces
Research Directions for Cross Reality Interfaces
Mark Billinghurst
 
@Call @Girls Pune 0000000000 Riya Khan Beautiful Girl any Time
@Call @Girls Pune 0000000000 Riya Khan Beautiful Girl any Time@Call @Girls Pune 0000000000 Riya Khan Beautiful Girl any Time
@Call @Girls Pune 0000000000 Riya Khan Beautiful Girl any Time
amitchopra0215
 
一比一原版(msvu毕业证书)圣文森山大学毕业证如何办理
一比一原版(msvu毕业证书)圣文森山大学毕业证如何办理一比一原版(msvu毕业证书)圣文森山大学毕业证如何办理
一比一原版(msvu毕业证书)圣文森山大学毕业证如何办理
uuuot
 

Recently uploaded (20)

this resume for sadika shaikh bca student
this resume for sadika shaikh bca studentthis resume for sadika shaikh bca student
this resume for sadika shaikh bca student
 
STKI Israeli Market Study 2024 final v1
STKI Israeli Market Study 2024 final  v1STKI Israeli Market Study 2024 final  v1
STKI Israeli Market Study 2024 final v1
 
MYIR Product Brochure - A Global Provider of Embedded SOMs & Solutions
MYIR Product Brochure - A Global Provider of Embedded SOMs & SolutionsMYIR Product Brochure - A Global Provider of Embedded SOMs & Solutions
MYIR Product Brochure - A Global Provider of Embedded SOMs & Solutions
 
What's Next Web Development Trends to Watch.pdf
What's Next Web Development Trends to Watch.pdfWhat's Next Web Development Trends to Watch.pdf
What's Next Web Development Trends to Watch.pdf
 
The Rise of Supernetwork Data Intensive Computing
The Rise of Supernetwork Data Intensive ComputingThe Rise of Supernetwork Data Intensive Computing
The Rise of Supernetwork Data Intensive Computing
 
Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...
 
Data Protection in a Connected World: Sovereignty and Cyber Security
Data Protection in a Connected World: Sovereignty and Cyber SecurityData Protection in a Connected World: Sovereignty and Cyber Security
Data Protection in a Connected World: Sovereignty and Cyber Security
 
Verti - EMEA Insurer Innovation Award 2024
Verti - EMEA Insurer Innovation Award 2024Verti - EMEA Insurer Innovation Award 2024
Verti - EMEA Insurer Innovation Award 2024
 
Why do You Have to Redesign?_Redesign Challenge Day 1
Why do You Have to Redesign?_Redesign Challenge Day 1Why do You Have to Redesign?_Redesign Challenge Day 1
Why do You Have to Redesign?_Redesign Challenge Day 1
 
Running a Go App in Kubernetes: CPU Impacts
Running a Go App in Kubernetes: CPU ImpactsRunning a Go App in Kubernetes: CPU Impacts
Running a Go App in Kubernetes: CPU Impacts
 
UiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs ConferenceUiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs Conference
 
Performance Budgets for the Real World by Tammy Everts
Performance Budgets for the Real World by Tammy EvertsPerformance Budgets for the Real World by Tammy Everts
Performance Budgets for the Real World by Tammy Everts
 
20240702 QFM021 Machine Intelligence Reading List June 2024
20240702 QFM021 Machine Intelligence Reading List June 202420240702 QFM021 Machine Intelligence Reading List June 2024
20240702 QFM021 Machine Intelligence Reading List June 2024
 
How Netflix Builds High Performance Applications at Global Scale
How Netflix Builds High Performance Applications at Global ScaleHow Netflix Builds High Performance Applications at Global Scale
How Netflix Builds High Performance Applications at Global Scale
 
DealBook of Ukraine: 2024 edition
DealBook of Ukraine: 2024 editionDealBook of Ukraine: 2024 edition
DealBook of Ukraine: 2024 edition
 
Observability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetryObservability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetry
 
Cookies program to display the information though cookie creation
Cookies program to display the information though cookie creationCookies program to display the information though cookie creation
Cookies program to display the information though cookie creation
 
Research Directions for Cross Reality Interfaces
Research Directions for Cross Reality InterfacesResearch Directions for Cross Reality Interfaces
Research Directions for Cross Reality Interfaces
 
@Call @Girls Pune 0000000000 Riya Khan Beautiful Girl any Time
@Call @Girls Pune 0000000000 Riya Khan Beautiful Girl any Time@Call @Girls Pune 0000000000 Riya Khan Beautiful Girl any Time
@Call @Girls Pune 0000000000 Riya Khan Beautiful Girl any Time
 
一比一原版(msvu毕业证书)圣文森山大学毕业证如何办理
一比一原版(msvu毕业证书)圣文森山大学毕业证如何办理一比一原版(msvu毕业证书)圣文森山大学毕业证如何办理
一比一原版(msvu毕业证书)圣文森山大学毕业证如何办理
 

Angular - Chapter 7 - HTTP Services

  • 3. www.webstackacademy.com Introduction to HTTP • Hyper Text Transfer Protocol (HTTP) is the client-server network protocol that has been in use by the World Wide Web (WWW) since 1990. • HTTP protocol is defined in RFC 7230 as per IETF standardization • It is one of the application layer protocols in the TCP/IP suite of protocols. • Whenever you are browsing the web, your browser will be sending HTTP request messages for various Resources (HTML pages, images etc..) and fetch them from the server
  • 4. www.webstackacademy.com Introduction to HTTP • Web servers handle these requests as a HTTP server by returning response messages that contain the requested resource. The client "pulls" the data from the server rather than the server "push" • HTTP is a Stateless protocol. This means the current request does not know what has been done in the previous requests. • HTTP permits negotiating of data type and representation, so as to allow systems to be built independently of the data being transferred. • In summary we can say HTTP is a application-level protocol for distributed, collaborative, hypermedia information systems.
  • 5. www.webstackacademy.com HTTP methods HTTP supports a set of methods, out of which four are very important and frequently used. Method Description GET The GET method is used to retrieve information from the given server using a given URI. DELETE Removes all current representations of the target resource given by a URI PUT Replaces all current representations of the target resource with the uploaded content POST A POST request is sent by the client to the server with all the data collected in the client end
  • 6. www.webstackacademy.com HTTP response code Upon receiving HTTP request, the server provides appropriate responses. They are categorized as follows: Code Category Description 1XX Informational Request received, server is continuing the process. 2XX Success The request was successfully received, understood, accepted and serviced. 3XX Redirection Further action must be taken in order to complete the request. 4XX Client Error The request contains bad syntax or cannot be understood. 5XX Server Error The server failed to fulfil an apparently valid request.
  • 7. www.webstackacademy.com HTTP response code - Examples Code Category Description 100 Continue The server received the request and in the process of giving the response. 200 OK The request is fulfilled. 301 Resource moved The client should issue a new request to the new location. 400 Bad Request Server could not interpret or understand the request, probably syntax error in the request message. 401 Authentication Required The requested resource is protected, and require client’s credential (username/password). 403 Forbidden Server refuses to supply the resource, regardless of identity of client. 404 Not Found The requested resource cannot be found in the server. 500 Internal Server Error Server is confused, often caused by an error in the server-side program responding to the request. 501 Method Not Implemented The request method used is invalid
  • 9. www.webstackacademy.com REST Interfaces • REST stands for REpresentational State Transfer. • REST is a web standards based architecture and that uses HTTP as the underlying protocol for communication. • It has a notion of "resource" where everything revolves around that. The resource is accessed by a common interface using HTTP standard methods. • REST was first introduced by Roy Fielding in year 2000.
  • 10. www.webstackacademy.com RESTful Web Services • A web service is a collection of open protocols and standards used for exchanging data between applications over the internet. • Web services based on REST Architecture are known as RESTful Web Services. These web services use HTTP methods to implement the concept of REST architecture. • Since HTTP offers two way communication methods, RESTful web service added a layer on top of it to implement meaningful web services using URI.
  • 11. www.webstackacademy.com Characteristics of REST • Three characteristics of REST:  Stateless: Client data is not stored on the server between interactions and the session is stored client-side (typically in session storage).  Client <-> Server: There is a “separation of concerns” between the frontend (client) and the backend (server). They operate independently of each other and both are replaceable.  Cache: Data from the server can be cached on the client, which can improve performance speed. • In addition to these three fundamental features of REST, there is also a uniform approach to the composition of URLs. This allows for a standardization of service, which prior to the introduction of REST, did not exist.
  • 12. www.webstackacademy.com Characteristics of REST • For example, a GET request to /courses, should yield all the courses in the database, whereas a GET request to /courses/20 would render the course with ID of 20. • Similarly, REST utilizes standard methods like GET, PUT, DELETE and POST to perform actions. • Today every major web service provider expose RESTful interfaces (called as REST APIs) using which client applications can enable client application developers develop application with ease
  • 13. www.webstackacademy.com A Brief about JSON • JSON: JavaScript Object Notation. • It is a lightweight data-interchange format, easy for humans to read and write. • All programming languages support them, easy to parse and interpret • One of the common standards used in data exchange for client-server communication. Servers as an alternative option for other data representations (ex: XML) • Data is represented as name-value pairs and array data types.
  • 14. www.webstackacademy.com JSON - Example { "firstName": “WebStack", "lastName“ : “Academy", “domain“ : “Education”, "phoneNumber": [ { "type": “landline", "number": “91-80-41289576" }, { "type": “mobile", "number": “8095557334" } ], }
  • 15. www.webstackacademy.comwww.webstackacademy.com HTTP services in Angular (Practical implementing in Angular)
  • 16. www.webstackacademy.com Make the Angular and related import paths import { HttpModule } from '@angular/http'; @NgModule({ declarations: [ AppComponent, HttpComponent, ], imports: [ BrowserModule, HttpModule // Import HTTP module here ], providers: [ EndPointServiceService ], }) 1. Import HTTP into app.module.ts
  • 17. www.webstackacademy.com 2. Accessing HTTP Access your HTTP service via constructor and access methods myPosts: any[]; private myURL = 'http://jsonplaceholder.typicode.com/posts'; constructor(private myHttp: Http) { // By default populate all posts.... myHttp.get(this.myURL).subscribe(response => { console.log(response.json()); this.myPosts = response.json(); }); }
  • 18. www.webstackacademy.com HTTP methods in Angular Here are the HTTP method details in Angular Method Definition GET get(url: string, options?: RequestOptionsArgs): Observable<Response> DELETE delete(url: string, options?: RequestOptionsArgs): Observable<Response> PUT put(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> POST post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> • NOTE: All functions return Observarable, you need to subscribe to get actual return values / error codes • Response type has got multiple fields, which can be obtained from Angular official documentation (https://angular.io/api/http/Response)
  • 20. www.webstackacademy.com Separation of Concern (SoC) - Concept • In computer science, separation of concerns (SoC) is a design principle for separating a computer program into distinct sections, such that each section addresses a separate concern. • A concern is a set of information that affects the code of a computer program (Functionality). • It is always a good practise to implement SoC well in your program, so that is becomes modular. • By making it modular we get other benefits in terms of re-usability, maintainability and simplifies development process.
  • 21. www.webstackacademy.com Separation of Concern (SoC) - Implementation • Practically it is achieved by encapsulating information inside a section of code that has a well-defined interface. • The section of code which is interested, will invoke this interface and obtain required information • This is also called as data encapsulation is a means of information hiding. The calling section will not know the detail orientation but only concerned about its objective • Typically these interfaces are methods / APIs and implemented via various OOP mechanisms – Classes, Constructors etc.. • In Angular also we have used these concepts already!
  • 23. www.webstackacademy.com Separation of Concern (SoC) in Angular • In Angular, we have seen separation of concern happening at component level as follows:  Template - HTML file  Style - CSS file  Business Logic - TS file • The main goal of the component is to deal with business logic related to view (Template + Style) • When it comes to dealing with HTTP services (ex: Fetching course list from Firebase) it should NOT be done as a part of component to adhere to SoC • The idea is to implement a service and access them via a method. This way you are “delegating" the action to a service. In this process you also achieve benefits of SoC.
  • 24. www.webstackacademy.com Separation of Concern (SoC) in Angular - Problem export class HttpComponent implements OnInit { myPosts: any[]; private myURL = 'http://jsonplaceholder.typicode.com/posts'; // Method for creating a new post createNewPost(userTitle: HTMLInputElement) { let newPost = { title: userTitle.value }; this.myHttp.post(this.myURL,JSON.stringify(newPost)).subscribe( response => { console.log(response.json()); this.myPosts.splice(0,0,newPost); }); }
  • 25. www.webstackacademy.com Separation of Concern (SoC) in Angular - Solution export class NewHttpComponentComponent implements OnInit { myPosts: any[]; constructor(private service: EndPointServiceService) { } createNewPost(userTitle: HTMLInputElement) { let newPost = { title: userTitle.value }; this.service.createPost(newPost).subscribe ( response => { this.myPosts.splice(0,0,newPost); }); }
  • 27. www.webstackacademy.com HTTP Errors • During the HTTP communication there could be many errors that could be happening • The application should capture errors and handle them appropriately HTTP Errors Unexpected Errors Expected Errors • Offline Server • N/W down • API Error • ……. • Not found (404) • Bad request (400) • Auth Failure (401) • …….
  • 28. www.webstackacademy.com HTTP Errors – Handling in Angular deleteExistingPost (dPost){ this.service.deletePost(dPost).subscribe ( response => { console.log("Post deleted successfully"); let dPostIndex = this.myPosts.indexOf(dPost); this.myPosts.splice(dPostIndex,1); }, error => { if (error.status == 404) // Expected Error alert ("Post already deleted"); else { // Unexpected Error alert ("An unexpected error occurred"); console.log(error); } }); }
  • 30. www.webstackacademy.com Building re-usable services • In HTTP based services, the common operations remain the same • In such cases each service may not want to implement the same methods. In order to achieve that services can be made re-usable using inheritance Step-1: Create a new TS file (ex: generic.service.ts) and import all HTTP methods into it export class GenericService { constructor(myURL: string, myHttp : Http) { } getPosts() { … } createPost(userPost) { … } updatePost(userPost) { … } deletePost(userPost) { … } } }
  • 31. www.webstackacademy.com Building re-usable services Step-2: From the service’s main class, inherit this class. Also use constructor of the parent to pass parameters and initialization. export class EndPointServiceService extends GenericService { } super(myURL, myHttp);
  • 32. www.webstackacademy.com Exercise • Create a GITHub followers page by accessing REST API provided by the GIT • Example URL: https://api.github.com/users/devendradora/followers
  • 33. www.webstackacademy.com Exercise • Ensure you apply following learnings:  New component to handle the main business logic  New re-usable service interacting with REST API  HTTP error handling  Directives for rendering all followers  CSS changes to display the follower names in a user friendly way  Display the following attributes:  Avatar (Profile picture)  GIT profile URL  Login name
  • 34. www.webstackacademy.com WebStack Academy #83, Farah Towers, 1st Floor, MG Road, Bangalore – 560001 M: +91-809 555 7332 E: training@webstackacademy.com WSA in Social Media: