2017-11-09 2 views
1

Angular2를 사용하여 웹 API에 배열을 보낼 수 없습니다.Angular2 및 Typescript를 사용하여 웹 API에 배열을 보내는 방법

apiData(command?: string | null, array?: string[] | null): Observable<void> { 
    //let url_ = this.baseUrl + "/api/Data/command?"; 
    let url_ = "/api/Data/command?"; 

    if (command !== undefined) 
     url_ += "command=" + encodeURIComponent("" + command) + "&"; 
    url_ = url_.replace(/[?&]$/, ""); 

    //const content_ = JSON.stringify(array); 

    if (array !== undefined) 
     array && array.forEach(item => { url_ += "array=" + encodeURIComponent("" + item) + "&"; }); 



    let options_: any = { 
     //data: content_, 
     method: "post", 
     headers: new Headers({ 
      "Content-Type": "application/json", 
     }) 
    }; 

을 그리고 API는 다음과 같습니다 : 내 타이프에서 나는이와 API를 호출하고있어

[Produces(typeof(void))] 
    [HttpPost("command")] 
    public HttpResponseMessage PostData(string command, string[] array) 
    { 

API가 배열에 정확한 금액 행을 수신하지만, 위의 예를 사용하여 그들이 모두 "[object Object]"입니다.

JSON.stringify (배열)를 사용하여 Data : (예제에서 주석 처리 한 경우)를 통해 전송하면 웹 API는 빈 문자열 만 가져옵니다. 내가 보내고있는 배열은 JSON입니다.

이 방법은 Angularjs에서 작동하지만 어떤 이유로이 기능을 사용할 수 없습니다.

+0

응답 '[objectObject]'가 표시됩니다. 구성 요소 수준 또는보기에서? –

답변

0

서비스에서 게시 방법을 사용할 수 있습니다.

constructor(private _http: Http){} 
apiData(command?: string | null, array?: string[] | null): Observable<void> { 

// your code 
return this._http.post(url, array, options) 
.map(
    // response logic 
) 
.catch(
    // exception handling 
); 
} 

구성 요소는 :

constructor(private _service : AboveServiceComponent) 
getStatusofSentData(){ 
this._service.subscribe(
res => { 
// get response 
}, 
err => { 
// handle error if any 
} 
) 
} 
0

이 같이 사용하려고 할 수 있습니다.

apiData(command?: string | null, array?: string[] | null): Observable<void> { 
    //let url_ = this.baseUrl + "/api/Data/command?"; 
    let url_ = "/api/Data/command?"; 

    if (command !== undefined) 
     url_ += "command=" + encodeURIComponent("" + command) + "&"; 
    url_ = url_.replace(/[?&]$/, ""); 

    //const content_ = JSON.stringify(array); 

    let data: any = { command: url_, array: array}; 

    let options_: any = { 
    data: JSON.stringify(data), 
    method: "post", 
    headers: new Headers({ 
     "Content-Type": "application/json", 
    }) 
}; 
관련 문제