SlideShare ist ein Scribd-Unternehmen logo
1 von 34
Downloaden Sie, um offline zu lesen
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:

Weitere ähnliche Inhalte

Was ist angesagt?

Angular Introduction By Surekha Gadkari
Angular Introduction By Surekha GadkariAngular Introduction By Surekha Gadkari
Angular Introduction By Surekha GadkariSurekha Gadkari
 
Angular 10 course_content
Angular 10 course_contentAngular 10 course_content
Angular 10 course_contentNAVEENSAGGAM1
 
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 projectJadson Santos
 
Sharing Data Between Angular Components
Sharing Data Between Angular ComponentsSharing Data Between Angular Components
Sharing Data Between Angular ComponentsSquash Apps Pvt Ltd
 
The New JavaScript: ES6
The New JavaScript: ES6The New JavaScript: ES6
The New JavaScript: ES6Rob Eisenberg
 
Angular Data Binding
Angular Data BindingAngular Data Binding
Angular Data BindingDuy Khanh
 
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event HandlingWebStackAcademy
 
Building blocks of Angular
Building blocks of AngularBuilding blocks of Angular
Building blocks of AngularKnoldus Inc.
 
Angular Interview Questions & Answers
Angular Interview Questions & AnswersAngular Interview Questions & Answers
Angular Interview Questions & AnswersRatnala Charan kumar
 
Angular tutorial
Angular tutorialAngular tutorial
Angular tutorialRohit Gupta
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation洪 鹏发
 
Angular 5 presentation for beginners
Angular 5 presentation for beginnersAngular 5 presentation for beginners
Angular 5 presentation for beginnersImran Qasim
 
Angular 16 – the rise of Signals
Angular 16 – the rise of SignalsAngular 16 – the rise of Signals
Angular 16 – the rise of SignalsCoding Academy
 
Angular data binding
Angular data binding Angular data binding
Angular data binding Sultan Ahmed
 
Angular components
Angular componentsAngular components
Angular componentsSultan Ahmed
 

Was ist angesagt? (20)

Angular Introduction By Surekha Gadkari
Angular Introduction By Surekha GadkariAngular Introduction By Surekha Gadkari
Angular Introduction By Surekha Gadkari
 
Angular Directives
Angular DirectivesAngular Directives
Angular Directives
 
Angular 10 course_content
Angular 10 course_contentAngular 10 course_content
Angular 10 course_content
 
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
 
Sharing Data Between Angular Components
Sharing Data Between Angular ComponentsSharing Data Between Angular Components
Sharing Data Between Angular Components
 
The New JavaScript: ES6
The New JavaScript: ES6The New JavaScript: ES6
The New JavaScript: ES6
 
Angular Data Binding
Angular Data BindingAngular Data Binding
Angular Data Binding
 
Angular overview
Angular overviewAngular overview
Angular overview
 
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event Handling
 
Angular 14.pptx
Angular 14.pptxAngular 14.pptx
Angular 14.pptx
 
Building blocks of Angular
Building blocks of AngularBuilding blocks of Angular
Building blocks of Angular
 
Angular Interview Questions & Answers
Angular Interview Questions & AnswersAngular Interview Questions & Answers
Angular Interview Questions & Answers
 
Angular tutorial
Angular tutorialAngular tutorial
Angular tutorial
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
 
Modern JS with ES6
Modern JS with ES6Modern JS with ES6
Modern JS with ES6
 
Angular Basics.pptx
Angular Basics.pptxAngular Basics.pptx
Angular Basics.pptx
 
Angular 5 presentation for beginners
Angular 5 presentation for beginnersAngular 5 presentation for beginners
Angular 5 presentation for beginners
 
Angular 16 – the rise of Signals
Angular 16 – the rise of SignalsAngular 16 – the rise of Signals
Angular 16 – the rise of Signals
 
Angular data binding
Angular data binding Angular data binding
Angular data binding
 
Angular components
Angular componentsAngular components
Angular components
 

Ähnlich wie Angular - Chapter 7 - HTTP Services

0_Leksion_Web_Servers (1).pdf
0_Leksion_Web_Servers (1).pdf0_Leksion_Web_Servers (1).pdf
0_Leksion_Web_Servers (1).pdfZani10
 
Rest WebAPI with OData
Rest WebAPI with ODataRest WebAPI with OData
Rest WebAPI with ODataMahek Merchant
 
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 : 1Ben 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.ppt20521742
 
Html intake 38 lect1
Html intake 38 lect1Html intake 38 lect1
Html intake 38 lect1ghkadous
 
Web Technologies Notes - TutorialsDuniya.pdf
Web Technologies Notes - TutorialsDuniya.pdfWeb Technologies Notes - TutorialsDuniya.pdf
Web Technologies Notes - TutorialsDuniya.pdfRaghunathan52
 
Web Technologies Notes - TutorialsDuniya.pdf
Web Technologies Notes - TutorialsDuniya.pdfWeb Technologies Notes - TutorialsDuniya.pdf
Web Technologies Notes - TutorialsDuniya.pdfRaghunathan52
 
Introduction to Web Architecture
Introduction to Web ArchitectureIntroduction to Web Architecture
Introduction to Web ArchitectureChamnap Chhorn
 
ASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiTiago Knoch
 
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 3207Lori Head
 
REST API Recommendations
REST API RecommendationsREST API Recommendations
REST API RecommendationsJeelani Shaik
 
Api design and development
Api design and developmentApi design and development
Api design and developmentoquidave
 

Ähnlich wie 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
 

Mehr von 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 JourneyWebStackAcademy
 
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 SecondWebStackAcademy
 
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 CourseWebStackAcademy
 
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 OpportunitiesWebStackAcademy
 
Webstack Academy - Internship Kick Off
Webstack Academy - Internship Kick OffWebstack Academy - Internship Kick Off
Webstack Academy - Internship Kick OffWebStackAcademy
 
Building Your Online Portfolio
Building Your Online PortfolioBuilding Your Online Portfolio
Building Your Online PortfolioWebStackAcademy
 
Front-End Developer's Career Roadmap
Front-End Developer's Career RoadmapFront-End Developer's Career Roadmap
Front-End Developer's Career RoadmapWebStackAcademy
 
Angular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and AuthorizationAngular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and AuthorizationWebStackAcademy
 
Angular - Chapter 6 - Firebase Integration
Angular - Chapter 6 - Firebase IntegrationAngular - Chapter 6 - Firebase Integration
Angular - Chapter 6 - Firebase IntegrationWebStackAcademy
 
Angular - Chapter 5 - Directives
 Angular - Chapter 5 - Directives Angular - Chapter 5 - Directives
Angular - Chapter 5 - DirectivesWebStackAcademy
 
Angular - Chapter 3 - Components
Angular - Chapter 3 - ComponentsAngular - Chapter 3 - Components
Angular - Chapter 3 - ComponentsWebStackAcademy
 
JavaScript - Chapter 10 - Strings and Arrays
 JavaScript - Chapter 10 - Strings and Arrays JavaScript - Chapter 10 - Strings and Arrays
JavaScript - Chapter 10 - Strings and ArraysWebStackAcademy
 
JavaScript - Chapter 15 - Debugging Techniques
 JavaScript - Chapter 15 - Debugging Techniques JavaScript - Chapter 15 - Debugging Techniques
JavaScript - Chapter 15 - Debugging TechniquesWebStackAcademy
 
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 ModelWebStackAcademy
 
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 - ObjectsWebStackAcademy
 
JavaScript - Chapter 7 - Advanced Functions
 JavaScript - Chapter 7 - Advanced Functions JavaScript - Chapter 7 - Advanced Functions
JavaScript - Chapter 7 - Advanced FunctionsWebStackAcademy
 

Mehr von 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 5 - Directives
 Angular - Chapter 5 - Directives Angular - Chapter 5 - Directives
Angular - Chapter 5 - Directives
 
Angular - Chapter 3 - Components
Angular - Chapter 3 - ComponentsAngular - Chapter 3 - Components
Angular - Chapter 3 - Components
 
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
 

Kürzlich hochgeladen

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 

Kürzlich hochgeladen (20)

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 

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: