angular - 返回函数的 Angular HTTP 请求
问题描述
我正在尝试将 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 中重写它?
解决方案
您可以在这里查看与您的代码几乎相似的内容 -
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);
});
}
}
推荐阅读
- nix - 具有自定义用户 systemd 单元的 Nixos 容器
- sql - 向我的 sql 查询添加 distinct 会使其加载很长时间并且无法正常工作
- r - 在R中将多个数据帧的行绑定到一个数据帧中
- php - 如何将哈希密码从注册连接到登录 PHP/MySQL
- javascript - Chrome扩展历史API的代理回调函数
- docker - 无法使用前端 dockerfile 解决
- r - 在数据库中保存/检索 R 对象,或 R 中对象持久性的其他解决方案
- reactjs - 条件反应返回语句
- xml - 如何使用pyspark从xml的每个嵌套节点创建一个表
- java - 如何垂直格式化多行列表