https://www.concretepage.com/angular-2/angular-2-http-get-parameters-headers-urlsearchparams-requestoptions-example
By Arvind Rai,
May 19,2017
This page will walk through Angular 2 Http get() parameters + Headers + URLSearchParams + RequestOptions example. Angular
Headers
class is used to create headers. Angular
URLSearchParams
class is used to create URL parameters. Angular
RequestOptions
instantiates itself using instances of
,
and other request options such as url,method,search,body,withCredentials,responseType. These classes are imported from
@angular/http
API. Finally
Http.get()
uses instance of
to interact with the server. Though
is optional to use with
to send headers and parameters using angular in-memory web API. Find the code snippet from our example.
getBookById(bookId: string): Observable<Book[]> {
let myHeaders = new Headers();
myHeaders.append('Content-Type', 'application/json');
let myParams URLSearchParams();
myParams'id' bookId);
let options RequestOptions({ headers: myHeaders params: myParams });
return this.http.get(this.url options)
.map.extractData.catch.handleError);
}
Using
set()
or
append()
method of
and
Contents
- Technologies Used
- Headers
- URLSearchParams
- RequestOptionsArgs and RequestOptions
- Http.get() with Multiple Headers and Multiple Parameters
- Angular In-Memory Web API
- Complete Example
- Run Application
- References
- Download Source Code
Technologies Used
Find the technologies being used in our example.
1. Angular 4.0.0
2. TypeScript 2.2.0
3. Node.js 6.10.1
4. Angular CLI 1.0.0
5. Angular Compiler CLI 4.0.0
6. angular-in-memory-web-api@0.3.2
is the angular class that is used to configure request headers. Find the sample
instantiation.
let myHeaders ();
We can also pass headers as an argument while instantiating
class. Find the code snippet.
({ : 'Cache-Control''no-cache' });
To fetch,add and delete headers,sans-serif; font-size:14px">class has following methods.
append(name: string,value: string)
: Appends a header to existing list of header values for a given header name. We use
as follows.
myHeaders'Accept''text/plain');
myHeaders' application/xhtml+xml ');
Now the
Accept
header will have the following values.
Accept: text/plain application/xhtml+xml
set(name: string,value: string|string[])
: Sets or overrides header value for given name. It is used as follows.
. set' application/xml 'header will have only the following value.
: application/xml
delete(name: string)
: Deletes all header values for the given name. We use it as follows.
. deleteget(name: string) : string
: Returns first header that matches given name. Find the code snippet.
let acceptHeader = myHeadersgetAll(name: string) : string[]
: Returns list of header values for a given name.
let acceptHeaders .getAll );
If we want to add multiple headers,we can achieve it by
method as follows.
);
myHeaders);
If we want to add multiple headers by
method,we can achieve it as follows.
);
URLSearchParams
creates the query string in the URL. It is a map-like representation of URL search parameters. Find its constructor syntax.
constructor(rawParams?: string queryEncoder?: QueryEncoder)
Both arguments in the constructor are optional. Angular
queryEncoder
parameter is used to pass any custom
QueryEncoder
to encode key and value of the query string. By default
encodes keys and values of parameter using JavaScript
encodeURIComponent()
method.
Now we can instantiate
as given below.
let myParams Now we can fetch,add and delete parameters using following methods.
append(param: string,val: string) : void
: Appends parameter value to existing list of parameter values for a given parameter name. It is used to add values in multi-value fields or arrays in query string. If we write the code as given below.
myParams'names''John');
myParams'David'Then query parameter
names
will be an array. The query string will look like as given below.
?names[]=John&namesDavid
Server side code such as PHP will get
parameter value as an array.
set(param: string,val: string)
: Sets or overrides parameter value for given parameter name. We can use as follows.
'Bob' The query string will be as follows.
=Bob
delete(param: string) : void
: Deletes all parameter values for the given parameter name. Find the code snippet.
get(param: string) : string
: In case of multi-value fields,it returns the first value for given parameter name. Find the code snippet.
let nameParam = myParamsgetAll(param: string) : string[]
: Returns list of values for a given parameter name. Find the code snippet.
let namesParam .getAllIf we want to add multiple parameters,0)">'category' catg'writer' wtrIf we want to add multiple parameters by
);
RequestOptionsArgs and RequestOptions
RequestOptionsArgs
is an interface that is used to construct a
. The fields of
are url,params,headers,responseType.
is used to create request option. It is instantiated using
. It contains all the fields of the
interface. Now find the constructor of
class.
({method headers body url search
withCredentials responseType}?: RequestOptionsArgsIn our example we will use following fields.
headers
: Sets headers for HTTP request. It is of
class type.
params
: Sets query parameters in the URL. It is of
Now if we have instance of
();
myHeadersAnd instance of
();
myParamsThen
headers
params
can be passed to
let options });
Http.get() with Multiple Headers and Multiple Parameters
Angular
method performs a request with HTTP GET method. Find the arguments of
method.
get(url) : Response>
url
: This is the HTTP URL to hit the server using HTTP GET method.
RequestOptionsArgs
: This is optional in
method. This is used to create instance of
to send headers,parameters etc with
Now If we want to add multiple headers,we can do as follows.
();
myHeaders);
Find the code snippet for
with multiple headers and multiple URL parameters.
getBooksAfterFilter(catg{
let myHeaders ();
myHeaders);
myHeaders);
let myParams ();
myParams);
myParams);
let options });
return this}
Angular In-Memory Web API
Angular provides in-memory web API to process HTTP request in test environment. In case we don't have actual server URL,we can use angular in-memory web API for testing our angular
Http
methods. It provides a dummy URL which can be changed by actual URL later. It returns an
Observable
of HTTP
Response
object in the manner of a RESTy web api. In our example we are using in-memory web API to get and post data. To use it in our angular application we need to follow below steps.
Step-1
: Add
angular-in-memory-web-api
in
dependencies
block in
package.json
file as given below.
"angular-in-memory-web-api""~0.3.2"
Step-2
: Run
npm install
command to download
.
Step-3
: Create a class implementing
InMemoryDbService
interface. In our example we are creating an in-memory DB for books. Find our class for our in-memory DB.
book-data.ts
import { InMemoryDbService } from 'angular-in-memory-web-api';
export class BookData implements {
createDb() {
let books = [
{ id'1' name'Angular 2 by Krishna' category'Angular' writer'Krishna' },
'2''AngularJS by Krishna''3''Angular 2 by Vishnu''Vishnu'
'4''Core Java by Vishnu''Java''5''JSP & Servlet by Vishnu''6''JPA by Vishnu''7''Hibernate by Krishna''Hibernate'}
];
return {books};
}
To interact with DB,URL will be
api/books
Step-4
: Before using DB we need to configure our above class in application module using
imports
metadata of
@NgModule
InMemoryWebApiModule.forRoot(BookDataFind the application module.
InMemoryWebApiModule ;
import BookData './book-data';
@NgModule({
---------
imports: [
BrowserModule
HttpModule)
]
---------
})
Find the
link
for more information on in-memory web API.
Complete Example
Find the complete example.
book.service.ts
Injectable '@angular/core'Http RequestOptions '@angular/http'Observable 'rxjs';
import Book './book'@Injectable()
export class BookService {
url = "api/books";
constructor(private http:{ }
getAllBooks(): {
return this)
);
}
getBookById{
let myHeaders ();
myHeaders);
let myParams ();
myParams);
let options });
return this)
}
getBooksAfterFilter);
let myParams );
myParams);
let options }
private extractData(res{
let body = res.json();
return body.data;
}
private handleError (errorResponse | any{
console.error.message || error);
return .throwbook.component.ts
ComponentOnInit NgForm '@angular/forms''./book.service'@Component({
selector'app-book'
templateUrl'./book.component.html'
styleUrls['./book.component.css'})
export class BookComponent implements {
allBooks[];
book;
filteredListOfBooks[];
errorMessageString;
dataAvailableById= true;
dataAvailableAfterFilter;
categories [
{name
}
];
writers [
'Krishna'
'Vishnu'}
];
constructor(private bookServiceBookService}
ngOnInit(): void {
this.getAllBooks();
}
getAllBooks.bookService()
.subscribe(
data => this.allBooks = data
error => this.errorMessage <any>error);
}
getBookById.dataAvailableById;
this.book = null;
this.getBookById)
=> {
if(data.length > 0{
this[];
} else {
this= false;
}
<any>error
);
}
getBooksAfterFilter(category.dataAvailableAfterFilter.filteredListOfBooks .getBooksAfterFilter)
{
if}
<any>error
);
}
bookById(bookByIdFormNgForm{
let bookId = bookByIdForm.controls'bookId'].value;
this);
}
filterBooks{
let catg ;
let wtr ;
thisbook.component.html
<h3>Book Details</h3>
<table>
<tr><th> Id</th> <th>Name</th><th>Category</th><th>Writer</th></tr>
<tr *ngFor="let bk of allBooks" >
<td>{{bk.id}}</td> <td>{{bk.name}}<td>{{bk.category}}<td>{{bk.writer}}</td>
</tr>
</table>
<h3>Get Book by ID <div>
<form #bookByIdForm= "ngForm" (ngSubmit)"bookById(bookByIdForm)">
<div>
Enter Book Id: <input name"bookId" ngModel required #bookId"ngModel"</div>
<div> <br/>
<button [disabled]"bookByIdForm.invalid">Submit</button>
</div>
</form>
</div>
<br/>
<div *ngIf"bookByIdForm.submitted""book; else loading">
<table>
</th></tr>
<tr>
<td>{{book.id}}<td>{{book.name}}<td>{{book.category}}<td>{{book.writer}}</td>
</tr>
</table>
</div>
<ng-template #loading"dataAvailableById; else notAvailable">
Loading data...
</div>
notAvailable> Data not Aavailable. </ng-template>
</ng-template>
</div>
<h3>Filter Books filterBookForm"filterBooks(filterBookForm)">
<div>
Category:
<select "category" ngModel>
<option value"" disabled>Select a Category</option>
<option *"let category of categories" [ngValue]"category.name">
{{ category.name }}
</option>
</select>
</div> <br/>
<div>
Writer:
"writer" >
>Select a Writer</option>
"let writer of writers" ["writer.name">
{{ writer.name }}
</div>
<div><br/>
<button>Submit</button>
"filterBookForm.submitted""filteredListOfBooks; else loading""let bk of filteredListOfBooks" >
</table>
"dataAvailableAfterFilter; else notAvailable"</div>
"errorMessage" [ngClass] "'error'"> {{errorMessage}} </div>
book.component.css
table {
border-collapse: collapse;
}
table th td : 1px solid black{
color: red;
font-size20pxbook.ts
export class {
id;
name;
category;
writer;
constructor{
}
app.component.ts
Component 'app-root'
template`
<app-book></app-book>
`
AppComponent {
app.module.ts
NgModule BrowserModule '@angular/platform-browser'FormsModule HttpModule } from './app.component'BookComponent './book.component'({
importsFormsModule],
declarations[
AppComponentBookComponent
providersBookService
bootstrapAppComponent
AppModule }
Run Application
To run the application,find following steps.
1.
Download source code using download link given on this page.
2.
In your angular CLI application,replace
src
folder.
3.
Add
"angular-in-memory-web-api": "~0.3.2"
file.
4.
Run
and then run
ng serve
5.
Now access the URL
http://localhost:4200
. Find the print screen.
Find the link for Angular 2
CRUD operation with Spring Boot.
Spring Boot REST + Angular 2 + JPA + Hibernate + MySQL CRUD Example
References
Http
Headers
URLSearchParams
RequestOptions
Angular 2 Http post() Example
Download Source Code
angular-2-http-get-parameters-headers-urlsearchparams-requestoptions-example.zip
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|