2017年5月13日 星期六

Angular2 HTTP Ajax 完整檔案

import { Http, Response, RequestOptions, Headers, Request, RequestMethod } from '@angular/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';

@Injectable()
export class HttpServiceService {
// 定義 http 協定
constructor(private http: Http) { };
// 定義以 Post 的方法發出請求 (網址, 傳送參數)
postRequest(url, data) {
// 定義常數 headers 並且新增自定義 header
const headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization', 'Bearer ' + localStorage.getItem('auth'));

// 定義常數 requestoptions 並且設定請求參數
const requestoptions = new RequestOptions({
method: RequestMethod.Post,
url: url,
headers: headers,
body: JSON.stringify(data)
});

// 實際發出請求 並且判斷特定請求代碼
return this.http
.request(new Request(requestoptions))
.map((res: Response) => {
// 請求成功時 回傳 json
if (res) {
if (res.status === 201) {
return res.json();
} else if (res.status === 200) {
return res.json();
}
}
// 請求失敗時
}).catch((error: any) => {
if (error.status === 500) {
return Observable.throw(new Error(error.status));
} else if (error.status === 401) {
return Observable.throw(new Error(error.status));
}
});
}
// 定義以 Get 的方法發出請求 (網址)
getRequest(url) {
// 定義常數 headers 並且新增自定義 header
const headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization', 'Bearer ' + localStorage.getItem('auth'));

// 定義常數 requestoptions 並且設定請求參數
const requestoptions = new RequestOptions({
method: RequestMethod.Get,
url: url,
headers: headers
});

// 實際發出請求 並且判斷特定請求代碼
return this.http
.request(new Request(requestoptions))
.map((res: Response) => {
// 請求成功時 回傳 json
if (res) {
if (res.status === 201) {
return res.json();
} else if (res.status === 200) {
return res.json();
}
}
// 請求失敗時
}).catch((error: any) => {
if (error.status === 500) {
return Observable.throw(new Error(error.status));
} else if (error.status === 401) {
return Observable.throw(new Error(error.status));
}
});
}
}

沒有留言:

張貼留言

remove last word from SQL query

SET @columnSql = SUBSTRING ( @columnSql , 1 , LEN ( @columnSql ) - 1 )