0

我正在尝试通过邮寄方式从后端获取数据。我正在尝试以下操作,但出现错误不起作用。

有人纠正我的发帖请求吗?

import { Injectable } from '@angular/core';
import { Http, Response, RequestOptions, Headers } from '@angular/http';

@Injectable()
export class ServerService {

  constructor(private http:Http) { }

    headers = new Headers();
    headers.append('Content-Type', 'application/json');

    postParam = {
        "clientId": "RETAIL",
        "spvParam": {
            "productCode": "PDO",
            "consigneeCountry": "MY",
            "salesOrgRef": "TH61",
            "salesOrgFacilityCode": "THBKK1",
            "salesOrgChnl": "eCommerce",
            "pickUpAcctRef": "5999999108",
            "facilityId": "MYKUL1"
        }
    }

    options = new RequestOptions({ headers: this.headers, body:this.postParam });


  getDataByPost(){
    alert('starts');
    let url = `http://mykullstc004004.apis.dhl.com:8003/efoms/getServiceProductV2`;
    this.http.post(url, {}, this.options ).subscribe(res => console.log( 'res', res ));
  }

}

更新

import { Component, OnInit } from '@angular/core';
import { ServerService } from './shared/service/server.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

    constructor(private server:ServerService){}

    ngOnInit(){
        this.server.getDataByPost();
    }

}
4

1 回答 1

3

根据@cruelEngine Body 应该是您请求的第二个参数而不是 requestOptions 的一部分,因此请尝试这样的代码:

@Injectable()
export class ServerService {
  postParam: any;
  options: any;

  constructor(private http:Http) {

    const headers = new Headers({'Content-Type' : 'application/json'});

    this.postParam = {
        "clientId": "RETAIL",
        "spvParam": {
            "productCode": "PDO",
            "consigneeCountry": "MY",
            "salesOrgRef": "TH61",
            "salesOrgFacilityCode": "THBKK1",
            "salesOrgChnl": "eCommerce",
            "pickUpAcctRef": "5999999108",
            "facilityId": "MYKUL1"
        }
    }

    this.options = new RequestOptions({ headers: this.headers });
  }

  getDataByPost(){
    alert('starts');
    let url = `http://mykullstc004004.apis.dhl.com:8003/efoms/getServiceProductV2`;
    this.http.post(url, JSON.stringify(this.postParam), this.options ).subscribe(res => console.log( 'res', res ));
  }

}
于 2018-04-25T11:26:39.617 回答