1. 程式人生 > >Angular 4/2 Http get() Parameters + Headers + URLSearchParams + RequestOptions Exam

Angular 4/2 Http get() Parameters + Headers + URLSearchParams + RequestOptions Exam

https://www.concretepage.com/angular-2/angular-2-http-get-parameters-headers-urlsearchparams-requestoptions-example

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 HeadersURLSearchParams 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 RequestOptions to interact with the server. Though RequestOptions is optional to use with Http.get(), but to send request headers or query/search parameters in the URL, we need to use them. On this page we will create an application that will use Http.get() 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 =newHeaders();
    myHeaders.append('Content-Type','application/json');let myParams =newURLSearchParams();
    myParams.append('id', bookId);let options =newRequestOptions({ headers: myHeaders,params: myParams });returnthis.http.get(this.url, options).map(this.extractData).catch(this.handleError);}
Using set() or append() method of URLSearchParams and Headers, we can add multiple parameters and headers, too. Now we will walk through complete example step by step.

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. [email protected]

Headers

Headers is the angular class that is used to configure request headers. Find the sample Headers instantiation.
let myHeaders =newHeaders();
We can also pass headers as an argument while instantiating Headers class. Find the code snippet.
let myHeaders =newHeaders({'Content-Type':'application/json','Cache-Control':'no-cache'});
To fetch, add and delete headers, Headers 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 append() as follows.
myHeaders.append('Accept','text/plain');    
myHeaders.append('Accept',' 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.
myHeaders.set('Accept',' application/xml ');
Now the Accept header will have only the following value.
Accept: application/xml 
delete(name: string): Deletes all header values for the given name. We use it as follows.
myHeaders.delete('Accept');
get(name: string) : string: Returns first header that matches given name. Find the code snippet.
let acceptHeader =  myHeaders.get('Accept');
getAll(name: string) : string[]: Returns list of header values for a given name.
let acceptHeaders =  myHeaders.getAll ('Accept');

If we want to add multiple headers, we can achieve it by set() method as follows.
myHeaders.set('Content-Type','application/json');
myHeaders.set('Accept','text/plain');
If we want to add multiple headers by append() method, we can achieve it as follows.
myHeaders.append('Content-Type','application/json');
myHeaders.append('Accept','text/plain');

URLSearchParams

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 QueryEncoder encodes keys and values of parameter using JavaScript encodeURIComponent() method. 
Now we can instantiate URLSearchParams as given below.
let myParams =newURLSearchParams();
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.append('names','John');
myParams.append('names','David');
Then query parameter names will be an array. The query string will look like as given below.
?names[]=John&names[]=David
Server side code such as PHP will get names parameter value as an array. 
set(param: string, val: string): Sets or overrides parameter value for given parameter name. We can use as follows.
myParams.set('names','Bob');
The query string will be as follows.
?names=Bob
delete(param: string) : void: Deletes all parameter values for the given parameter name. Find the code snippet.
myParams.delete('names');
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 = myParams.get('names');
getAll(param: string) : string[]: Returns list of values for a given parameter name. Find the code snippet.
let namesParam = myParams.getAll('names');

If we want to add multiple parameters, we can achieve it by set() method as follows.
myParams.set('category', catg);
myParams.set('writer', wtr);
If we want to add multiple parameters by append() method, we can achieve it as follows.
myParams.append('category', catg);
myParams.append('writer', wtr);

RequestOptionsArgs and RequestOptions

RequestOptionsArgs is an interface that is used to construct a RequestOptions. The fields of RequestOptionsArgs are url, method, search, params, headers, body, withCredentials, responseType. 
RequestOptions is used to create request option. It is instantiated using RequestOptionsArgs. It contains all the fields of the RequestOptionsArgs interface. Now find the constructor of RequestOptions class.
constructor({method, headers, body, url, search,params, 
                 withCredentials, responseType}?:RequestOptionsArgs)
In our example we will use following fields. 
headers : Sets headers for HTTP request. It is of Headers class type. 
params: Sets query parameters in the URL. It is of URLSearchParams class type. 

Now if we have instance of Headers as follows.
let myHeaders =newHeaders();
myHeaders.append('Content-Type','application/json');
And instance of URLSearchParams as follows.
let myParams =newURLSearchParams();
myParams.append('id', bookId);
Then headers and params can be passed to RequestOptions as given below.
let options =newRequestOptions({ headers: myHeaders,params: myParams });

Http.get() with Multiple Headers and Multiple Parameters

Angular Http.get() method performs a request with HTTP GET method. Find the arguments of Http.get() method.
get(url:string, options?:RequestOptionsArgs):Observable<Response>
url: This is the HTTP URL to hit the server using HTTP GET method. 
RequestOptionsArgs: This is optional in Http.get() method. This is used to create instance of RequestOptions to send headers, parameters etc with Http.get() method. 

Now If we want to add multiple headers, we can do as follows.
let myHeaders =
            
           

相關推薦

Angular 4/2 Http get() Parameters + Headers + URLSearchParams + RequestOptions Exam

https://www.concretepage.com/angular-2/angular-2-http-get-parameters-headers-urlsearchparams-requestoptions-example May 19, 2

angular 1.6 $http.get(...).success is not a function 解決辦法

一、現狀 使用了angular1.6最新版,執行以前的專案報錯,按F12開啟除錯介面,控制檯輸出以下資訊$http.get(...).success is not a function,也就是說找不到success方法,同樣也找不到error方法。 二、

Angular 4.3 HttpClient (Angular訪問 REST Web 服務) 一、Http 請求示例(Get

連結 開發工具:Visual Studio Code 在Angular 4.3中引入了新的HttpClientModule。 這個新模組可以在@ angular / common / http包中找到,並且可以完全重新實現前一個HttpModule。新的Ht

阿裏雲apt-get安裝包時Err:2 http://mirrors.cloud.aliyuncs.com/ubuntu xenial-security/main amd64 git amd64 1:2.7.4-0ubuntu1.2 404 Not Found

spa http 百度一 main operation 服務器 這不 may fix 新部署的雲服務器出現如下錯誤: root@iZj6cbjalvhsw0fhndmm5xZ:~# apt-get install git Reading package lists.

[Angular] Read Custom HTTP Headers Sent by the Server in Angular

conf nor update names fault pan table tom color By default the response body doesn’t contain all the data that might be needed in y

Centos 7.4http-2.4 的基本實現和 https 的實現

http-2.4 https 1.建立httpd服務,要求: 1) 提供兩個基於名稱的虛擬主機www1, www2;要求每個虛擬主機都有單獨的錯誤日誌和訪問日誌; 2) 通過www1的/server-status提供狀態信

Could not load file or assembly 'System.Net.Http, Version=4.2.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencie

Could not load file or assembly 'System.Net.Http, Version=4.2.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The locate

http Get Post response headers

常見狀態碼: 200 OK                       //客戶端請求成功 400 Bad Request             //客戶端請求有語法錯誤,不能被伺服器所理解 401 Unauthorized              //請求未經授權

Failure to find net.sf.json-lib:json-lib:jar:2.4 in http://uk.maven.org/maven2/ was cached in...

Caused by: org.eclipse.aether.transfer.ArtifactNotFoundException: Failure to find net.sf.json-lib:json-lib:jar:1.5:2.4 in http://uk

Failure to transfer org.apache.maven.plugins:maven-surefire-plugin:pom:2.12.4 from http://repo1.mave

maven專案pom.xml報錯:Failure to transfer org.apache.maven.plugins:maven-surefire-plugin:pom:2.12.4 from http://repo1.maven.org/maven2 w

ASP.NET Core 2.0和Angular 4:從頭開始構建用於車輛管理的Web應用程式

  目錄 介紹 背景 使用程式碼 I)伺服器端 a)先決條件 b)設定專案 c)設定資料庫 d)使用AutoMapper e)使用Swagger f)執行API II)客戶端 a)先決條件 b)設定專案 c)實現服務 d)

4.2.36.4HTTP之OkHttp(四): OkHttp原始碼解析

原始碼開始之前我先貼一段OkHttp請求網路的例項 OkHttpClient mOkHttpClient = new OkHttpClient(); final Request request = new Request.Builder() .url("

Angular 4 到 Angular6 http請求的變化

以下純屬個人學習中遇到的問題以及解決後的感悟,歡迎指點錯誤: 在Angular4 中 ,要用使用http請求伺服器資料,應該在constructor中匯入Http模組 , 如: constructor(private http: Http){}, 在使用時,使用this.http.get(u

Http,Https (SSL)的Url絕對路徑,相對路徑解決方案Security Switch 4.2 英文幫助文件

Security Switch 4.2 =================== Security Switch enables various ASP.NET applications to automatically switch requests for pages/r

【JavaScript】2.HttpGet與Post兩種請求方式的差異

Get和Post在面試中一般都會問到,一般的區別: (1)post更安全(不會作為url的一部分,不會被快取、儲存在伺服器日誌、以及瀏覽器瀏覽記錄中) (2)post傳送的資料更大(get有url長度限制) (3)post能傳送更多的資料型別(get只能傳送ASCII字元)

Jmeter入門2 http請求—簡單的get請求

http請求 箭頭 簡單 read sample get請求 blog 技術分享 我們 發送一個簡單的get http請求 1 啟動Jmeter,在測試計劃上點擊鼠標右鍵》添加》Threads(Users)》線程組 2 線程組界面。可設置線程數,幾秒啟動

Angular 4 - The Basics 筆記(1): Install

install rst logs nod first log 筆記 npm app Install Node.js Install Angular CLI sudo npm install -g @angular/cli Set-up new app

iScroll 4.2.5 中文API

clip 基本 包括 sla 大量 oot 屬性 con padding 下載iScroll4.2.5 iScroll的歷史 之所以iscroll會誕生,主要是因為無論是在iphone、ipod、android 或是更早前的移動webkit都沒有提供一種原生的方式來支持在一

零基礎學python-4.2 其它內建類型

介紹 src one 一個 tex == water 文件 div 這一章節我們來聊聊其它內建類型 1.類型type 在python2.2的時候,type是通過字符串實現的,再後來才把類型和類統一 我們再次使用上一章節的圖片來說明一些問題 我們通

jQuery treeTable v 1.4.2

ica select angularjs ron tree repeat style cond 4.2 angularJs版本: 如圖所示即為treeTable的效果,三個紅色框每個微一級 外科>骨科>骨科一病區 html: <table class=