我的帖子请求没有工作任何人在这里纠正我?

时间:2018-04-25 11:22:48

标签: angular angular-http angular-observable

我正试图通过帖子从后端获取数据。我正在尝试以下方法,但是错误不起作用。

任何人都要更正我的帖子请求吗?

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

}

1 个答案:

答案 0 :(得分:3)

因为Per @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 ));
  }

}