Ionic2 get和post請求樣例
在ionic2的service中使用http請求資料返回一個Promise:
首先在專案路徑下執行ionic g provider HomeService,會在專案的中生成一個providers的資料夾,裡面會生成一個home-service.ts檔案。
然後在你要在使用用service的component中注入HomeService,例如在home.ts中
import {HomeService} from "../../providers/home-service";
@Component({
selector: 'page-home',
templateUrl: 'home.html' ,
providers:[HomeService]
})
export class HomePage {
constructor(
public navCtrl: NavController,
public service:HomeService
) {
}
}
這樣就可以通過注入的service呼叫HomeService中的方法:
this.service.get().then(data=>{console.log(data)})
在service中我們定義get和post兩個方法,在方法裡面直接使用new Promise建立承諾,然後呼叫this.http.get(url,pramas,config)進行請求,在返回的資料中先要將資料轉換為json,這步通過map實現,然後後面是兩個回掉函式。
注意
在配置header的時候需要引入Headers通過append方法新增頭資訊。
傳入的請求引數如果是一個物件的話就需要通過JSON.stringify()將物件轉換為字串。
—————————最終程式碼樣例—————————————
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';
/*
Generated class for the HomeService provider.
See https ://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
@Injectable()
export class HomeService {
constructor(public http: Http) {
console.log('Hello HomeService Provider');
}
get() {
return new Promise((resolve, reject) => {
this.http.get(URL)
.map(res => res.json())
.subscribe(data => {
resolve(data);
}, err => {
reject(err);
})
})
}
//這種post方式在php中後臺無法獲取到資料,我們需要採用另外一種方式
post() {
let header = new Headers();
header.append('Content-Type', 'application/x-www-form-urlencoded');
let pramas = JSON.stringify({ username: "", password: "" })
return new Promise((resolve, reject) => {
this.http.post(URL, pramas, header)
.map(res => res.json())
.subscribe(data => resolve(data), err => reject(err))
})
}
//因為上面的請求引數在RequestPayload中,而下面的請求引數在formData中(具體可以看兩者的區別)
post2() {
let headers = new Headers({
'Content-Type': 'application/x-www-form-urlencoded'
});
let options = new RequestOptions({
headers: headers
});
let body= "username=admin&password=123456";
return new Promise((resolve, reject) => {
this.http.post(URL, body, options )
.map(res => res.json())
.subscribe(data => resolve(data), err => reject(err))
})
}
}
//或者使用以下方法將json進行引數化
private toQueryString(obj) {
let result = [];
for (let key in obj) {
key = encodeURIComponent(key);
let values = obj[key];
if (values && values.constructor == Array) {
let queryValues = [];
for (let i = 0, len = values.length, value; i < len; i++) {
value = values[i];
queryValues.push(this.toQueryPair(key, value));
}
result = result.concat(queryValues);
} else {
result.push(this.toQueryPair(key, values));
}
}
return result.join('&');
}
private toQueryPair(key, value) {
if (typeof value == 'undefined') {
return key;
}
return key + '=' + encodeURIComponent(value === null ? '' : String(value));
}
}
這樣就可以通過
post2(data) {
let headers = new Headers({
'Content-Type': 'application/x-www-form-urlencoded'
});
let options = new RequestOptions({
headers: headers
});
return new Promise((resolve, reject) => {
this.http.post(URL, this.toQueryString(data), options )
.map(res => res.json())
.subscribe(data => resolve(data), err => reject(err))
})
}
}
進行請求了。
相關推薦
Ionic2 get和post請求樣例
在ionic2的service中使用http請求資料返回一個Promise: 首先在專案路徑下執行ionic g provider HomeService,會在專案的中生成一個providers的資料夾,裡面會生成一個home-service.ts檔案。 然
Node.js使用superagent模擬GET/POST請求樣例
require url pre form 示例代碼 代碼 name use agent 示例代碼: var superagent = require(‘superagent‘); superagent.get("http://localhost:8091/user/all
C++:C語言實現HTTP的GET和POST請求例程參考 C++:C語言實現HTTP的GET和POST請求
C++:C語言實現HTTP的GET和POST請求 閱讀目錄 HTTP請求和IP/TCP 實現GET請求 實現POST請求: 參考: 回到頂部
發送get和post請求時常用的content-type
encode json數據格式 ima for www 下載 orm 文件上傳 服務器 常見的媒體格式類型如下: text/html : HTML格式 text/plain :純文本格式 text/xml : XML格式
HttpClient GET和POST請求
pri execute public methods gre col esp odt stringbu package com.rogue.hclient; import java.io.BufferedReader; import java.io.IOExceptio
http基本get和post請求
read exce pen timeout etc builder pri void tin get請求: private static void httpGet(){ BufferedReader br = null; HttpU
GET和POST請求的區別
cat nal 賬號 span asc 交互 cap 開發 code GET和POST請求的區別 GET請求GET /books/?sex=man&name=Professional HTTP/1.1Host: www.wrox.comUser-Agent: Mo
python request 接口測試get和post請求
.post .get access username int 用戶 post請求 運行 開發 開發IDE:pycharm python:2.7.10 get請求 # coding: UTF-8 #兼容中文字符,如果沒有這句,程序中有中文字符時,運行會報錯import
小程序的get和post請求頭的區別
type www 成功 ava form brush quest -type function 小程序在使用wx.request()接口 時 header 請求頭默認是這樣的 wx.request({ url: ‘test.php‘, //僅為示例,並非真實的接口
php-get和post請求
output class ray 工作日 打印 init print bsp clas 1.get請求 <?php //判斷20130101是否是工作日 //工作日對應結果為 0, 休息日對應結果為 1, 節假日對應的結果為 2; $url=‘http://www
PHP中使用CURL實現GET和POST請求
由於 protocol 對稱加密 即使 匯報 bst 接口 useragent 拷貝 一、什麽是CURL? cURL 是一個利用URL語法規定來傳輸文件和數據的工具,支持很多協議,如HTTP、FTP、TELNET等。最爽的是,PHP也支持 cURL 庫。使用php的cURL
CURL實現發送Get和Post請求(PHP)
結果 基本 釋放 初始 常用 header 理解 介紹 今天 1.cURL介紹 cURL 是一個利用URL語法規定來傳輸文件和數據的工具,支持很多協議,如HTTP、FTP、TELNET等。最爽的是,PHP也支持 cURL 庫。本文將介紹 cURL 的一些高級特性,以及
封裝curl的get和post請求
else 請求 enc con code urn gpo sta url /** * GET 請求 * @param string $url */ function http_get($url){ $oCurl = curl_init(); if(s
C#中Get和Post請求的同步及異步方法
iter epo charset result string pty streambuf div httpget 在C#中發起Http請求一般使用HttpWebRequest這個類,下文將使用這個HttpWebRequest對象來對Get和Post的同步及異步請求進行封裝:
get和post請求
OS nbsp alt 請求 ima body bsp .com bubuko get和post請求
js-Ajax-get和post請求
js Ajax get 1:get請求方式:// 1:創建XMLHttpRequest對象 var xhr; if (window.XMLHttpRequest) { // 其他類型的瀏覽器 xhr = new XMLHttpRequest(); } else { // ie瀏覽器
Http協議中GET和POST請求方法的區別
出場 請求參數 底層 情況下 -type 過去 firefox url sym GET和POST是HTTP請求的兩種基本方法,要說它們的區別,接觸過WEB開發的人都能說出一二。 最直觀的區別就是GET把參數包含在URL中,POST通過request body傳遞
get和post請求方法的區別
外衣 log ati 技術 告訴 alt 怎麽 yahoo 鏈接 GET和POST是HTTP請求的兩種基本方法,要說它們的區別,接觸過WEB開發的人都能說出一二。 最直觀的區別就是GET把參數包含在URL中,POST通過request body傳遞參數。 你可能自
ajax向服務器發出get和post請求
-c 效果 doc 假設 orm php 感覺 包含 只需要 假設有個網站A,它有一個簡單的輸入用戶名的頁面,界面上有兩個輸入框,第一個輸入框包含在一個form表單裏用來實現form提交,第二個輸入框是單獨的、沒有包含在form裏,下面就用這兩個輸入框來學習下jQuery的
http GET 和 POST 請求的優缺點、區別以及誤區
Get和Post在面試中一般都會問到,一般的區別: (1)post更安全(不會作為url的一部分,不會被快取、儲存在伺服器日誌、以及瀏覽器瀏覽記錄中) (2)post傳送的資料更大(get有url長度限制) (3)post能傳送更多的資料型別(get只能傳送ASCII字元) (4)