首页 > 解决方案 > 返回函数的 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 中重写它?

标签: angulartypescript

解决方案


您可以在这里查看与您的代码几乎相似的内容 -

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);
    });
  }
}

推荐阅读