Tuesday, October 25, 2022
Angular tutorial part 4 - Learn Angular The HTTP Module •Methods • Observable.toPromise • Error Handling • Header Pipes
Server communication
• The HTTP Module
•Methods
•
Observable.toPromise
• Error Handling
• Header
Pipes
Http
Module
• Http module basically is used to connect to resource
on the network
• and process the result.
• Returns an
observable
Http
module
• request: performs any type
of http request
• get: performs a
request with GET http method
• post: performs a
request with POST http method
• put: performs a
request with PUT http method
• delete: performs a
request with DELETE http method
• patch: performs a
request with PATCH http method
• head: performs a
request with HEAD http method
To use
http in component
•
Import httpmodule
in app module
• import { HttpClientModule } from '@angular/common/http';
• Add to imports ,
imports: [ HttpClientModule ],
in app module
•
Import the
following in component ts
• import { HttpClient, HttpHeaders,HttpHeaderResponse } from "@angular/common/http";
• Inject httpclient in constructor: constructor(private http: HttpClient) { }
Making
http post call
• Real time code
creates user record in mysql via springboot endpoint,angular basically calls
this springboot endpoint and passes and user class object.
•
• private url = 'http://127.0.0.1:8080/insertuser';
• CreateUser(user: User): Observable<any>{
• var httpOptions = {
• headers: new HttpHeaders({ 'Content-Type': 'application/json'})
• };
• console.log('value from service'+JSON.stringify(user));
• return this.http.post<User>(this.url,user,httpOptions);
•
Walk
through sample code
• loadItems() {
• return this.http.get(BASE_URL)
//basically a get call is made using the http module
• .map(res =>
res.json())/returns a json respononse
• .toPromise();
• }
• createItem(item:
Item) {
• return this.http.post(`${BASE_URL}`,
JSON.stringify(item), HEADER)
• //basically a post call is made on the http module
• .map(res =>
res.json()) //process the json response
• .toPromise();
• }
Http
Put and Delete
• updateItem(item:
Item) {
• return this.http.put(`${BASE_URL}${item.id}`,
• JSON.stringify(item),
HEADER)
• .map(res =>
res.json())
• .toPromise();
• }
• deleteItem(item:
Item) {
• return this.http.delete(`${BASE_URL}${item.id}`)
• .map(res =>
res.json())
• .toPromise();
• }
Using
Observable
• Observables
are really just functions that throw values
• . Objects called
observers define callback functions for next(), error(), and complete().•
Composed of subjects and observers
• A subject performs some logic and
notifies the
• observer at the appropriate
times
•
Observable.subscribe is used to check result of the
method
• We finalize an
observable stream by subscribing to it
• The subscribe
method accepts three event handlers
• onNext is called when new
data arrives
• onError is called when an
error is thrown
• onComplete is called when the
stream is completed
• source.subscribe(
• x =>
console.log('Next: ' + x),
• err =>
console.log('Error: ' + err),
• () =>
console.log('Completed'));
• Observable.
Error
handling
• We should always
handle errors
• Chain the .catch
method on an observable
• Pass in a callback
with a single error argument
•
this.http.get('users.json')
•
.catch(error => {
•
console.error(error);
•
return Observable.throw(error.json().error || 'Server
error');
• });
Using
Promise
• Promise is another way we can hit a network url and
assess the results. Promise is asynch ,that it waits for the response.
•
We
can chain any HTTP with toPromise
• Then we can use .then
and .catch to resolve the promise
• Headers can be
added,post of get can be done.
•
this.http.get('users.json')
•
.toPromise()
•
.then(res => res.json().data) //handle the data
•
.then(users => this.users = users)
• .catch(this.handleError);/if
error
Adding
Headers
• Import Headers and
RequestOptions:
• import {Headers,
RequestOptions} from 'angular2/http';
• Headers are an
instance of the Headers class
• Pass in an object
with each header as a key-value pair
• Used mainly to pass security token params
•
Then
pass this Headers instance into a new RequestOptions
• instance
•
let headers = new Headers({ 'Content-Type':
'application/json' });
•
let options = new RequestOptions({ headers: headers });
• this.http.post('users.json',
'{}', options);
Pipes
• •What are Pipes?
• • Built-in Pipes
• • Custom Pipes
• • Async Pipes
What
are pipes
• A pipe takes in
data as input and transforms it to a desired
• output
• We use them in our
templates with interpolation:
•
<p>User created on {{ created_at | date }}</p>
• Include parameters
to a pipe by separating them with a colon:
•
<p>User created on {{ created_at |
date:"MM/dd/yy" }}</p>
• Pipes are
chain-able:
• <p>User
created on {{ created_at | date | uppercase }}</p>
Build
in Pipes
• DatePipe
•
<p>User created on {{ user.created_at | date
}}</p>
• UpperCasePipe
•
<p>Middle Initial: {{ user.middle | uppercase
}}</p>
• LowerCasePipe
•
<p>Username: {{ user.username | lowercase
}}</p>
• CurrencyPipe
•
<p>Price Plan: {{ user.plan.price | currency }}</p>
• PercentPipe
• <p>Data
Usage: {{ user.usage | percent }}</p>
Build
your own custom pipes
•
import { Pipe, PipeTransform } from 'angular2/core';
• Create a class that
implements the PipeTransform interface
• and includes a transform
method:
•
export class ReversePipe implements PipeTransform {
•
transform(value:string, args:string[]) : any {
•
return value.reverse();
•
}
• }
Pipes
for Http calls
• Resolves async data
(observables/promises) directly in the template
• Skips the process
of having to manually subscribe to async methods
• in the component
and then setting those values for the template to
• bind to
• Component
attribute:
•
asyncAttribute<string> = new Promise((resolve,
reject) => {
•
setTimeout(() => resolve('Promise resolved'), 500);
•
})
• Template: <p>Async
result: {{asyncAttribute | async}}</p>
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment