SlideShare una empresa de Scribd logo
1 de 34
Descargar para leer sin conexión
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:

Más contenido relacionado

La actualidad más candente

Angular directives and pipes
Angular directives and pipesAngular directives and pipes
Angular directives and pipesKnoldus Inc.
 
Angular - Chapter 1 - Introduction
 Angular - Chapter 1 - Introduction Angular - Chapter 1 - Introduction
Angular - Chapter 1 - IntroductionWebStackAcademy
 
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 - Chapter 5 - Directives
 Angular - Chapter 5 - Directives Angular - Chapter 5 - Directives
Angular - Chapter 5 - DirectivesWebStackAcademy
 
Angular Interview Questions & Answers
Angular Interview Questions & AnswersAngular Interview Questions & Answers
Angular Interview Questions & AnswersRatnala Charan kumar
 
Angular - Chapter 3 - Components
Angular - Chapter 3 - ComponentsAngular - Chapter 3 - Components
Angular - Chapter 3 - ComponentsWebStackAcademy
 
Angular 8
Angular 8 Angular 8
Angular 8 Sunil OS
 
Angular tutorial
Angular tutorialAngular tutorial
Angular tutorialRohit Gupta
 
Angular interview questions
Angular interview questionsAngular interview questions
Angular interview questionsGoa App
 
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
 
Angular 4 Tutorial | What's New In Angular 4 | Angular Training | Edureka
Angular 4 Tutorial | What's New In Angular 4 | Angular Training | EdurekaAngular 4 Tutorial | What's New In Angular 4 | Angular Training | Edureka
Angular 4 Tutorial | What's New In Angular 4 | Angular Training | EdurekaEdureka!
 
Angular Introduction By Surekha Gadkari
Angular Introduction By Surekha GadkariAngular Introduction By Surekha Gadkari
Angular Introduction By Surekha GadkariSurekha Gadkari
 
Basics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdfBasics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdfKnoldus Inc.
 

La actualidad más candente (20)

Angular directives and pipes
Angular directives and pipesAngular directives and pipes
Angular directives and pipes
 
Angular - Chapter 1 - Introduction
 Angular - Chapter 1 - Introduction Angular - Chapter 1 - Introduction
Angular - Chapter 1 - Introduction
 
Angular Directives
Angular DirectivesAngular Directives
Angular Directives
 
Angular Directives
Angular DirectivesAngular Directives
Angular Directives
 
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 Basics.pptx
Angular Basics.pptxAngular Basics.pptx
Angular Basics.pptx
 
Angular - Chapter 5 - Directives
 Angular - Chapter 5 - Directives Angular - Chapter 5 - Directives
Angular - Chapter 5 - Directives
 
Angular Interview Questions & Answers
Angular Interview Questions & AnswersAngular Interview Questions & Answers
Angular Interview Questions & Answers
 
Angular overview
Angular overviewAngular overview
Angular overview
 
Angular - Chapter 3 - Components
Angular - Chapter 3 - ComponentsAngular - Chapter 3 - Components
Angular - Chapter 3 - Components
 
Angular 8
Angular 8 Angular 8
Angular 8
 
Angular tutorial
Angular tutorialAngular tutorial
Angular tutorial
 
Angular
AngularAngular
Angular
 
React js
React jsReact js
React js
 
Angular interview questions
Angular interview questionsAngular interview questions
Angular interview questions
 
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 4 Tutorial | What's New In Angular 4 | Angular Training | Edureka
Angular 4 Tutorial | What's New In Angular 4 | Angular Training | EdurekaAngular 4 Tutorial | What's New In Angular 4 | Angular Training | Edureka
Angular 4 Tutorial | What's New In Angular 4 | Angular Training | Edureka
 
Angular Lifecycle Hooks
Angular Lifecycle HooksAngular Lifecycle Hooks
Angular Lifecycle Hooks
 
Angular Introduction By Surekha Gadkari
Angular Introduction By Surekha GadkariAngular Introduction By Surekha Gadkari
Angular Introduction By Surekha Gadkari
 
Basics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdfBasics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdf
 

Similar a 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
 

Similar a 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
 

Más de 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 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 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
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic FunctionsWebStackAcademy
 

Más de 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
 

Último

Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
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
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
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
 
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
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 

Último (20)

Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
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
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
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
 
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
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 

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: