我正在尝试将AngularJS / JS代码重写为Angular / TS,以获取生成http请求并返回函数的自定义方法。但是,我被困在如何做到这一点。我的JS代码如下所示:
function generateRequest(method, url, headers, body) {
return {
method: method,
url: url,
headers: headers,
body: body
};
}
myService.customRequest = function (method, URL, headers, body, fncSuccess, fncFail) {
var point = www.someURL.com;
$http(generateRequest(method, point, headers, body)).then(function (response) {
if (typeof fnc == 'function') {
fnc(response.body);
}
}, function (response) {
if (response.status != 106) {
if (typeof fncFail == 'function') {
fncFail(response);
}
}
});
};
有人能告诉我如何使用HttpClient类在Angular / TS中重写它吗?
答案 0 :(得分:0)
你可以在这看一下你的代码 -
import { Http, Response, RequestOptions, Headers, Request, RequestMethod } from '@angular/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Rx';
@Injectable()
export class GlobalService {
constructor(
public http: Http,
) { }
generateRequest(url, method, body?, headers) {
const requestoptions = new RequestOptions({
method: method === 'post' ? RequestMethod.Post : RequestMethod.Get,
url: url,
headers: headers,
body: body || null
});
return requestoptions;
}
public customRequest(url: string, method, headers, body): any {
let point = www.someURL.com;
return this.http.request(new Request(this.setHeader(point, 'get', body, headers)))
.map((res: Response) => {
return [{status: res.status, json: res.json()}];
})
.catch((error: any) => {
return this.handleError(error);
});
}
}