【问题标题】:How to send an array to a web api with Angular2 and Typescript如何使用 Angular 和 Typescript 将数组发送到 Web api
【发布时间】:2017-11-09 16:23:20
【问题描述】:

我无法使用 Angular2 将数组发送到 Web api。在我的打字稿中,我用这个来调用 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 看起来像这样:

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

当使用上面的例子时,api 在数组中接收到正确数量的行,但它们都是“[object Object]”。

如果我使用 JSON.stringify(array) 并将其作为数据发送:(在我的示例中注释掉)web api 只会得到一个空字符串。我发送的数组是 JSON。

这种方法在 Angularjs 中有效,但由于某种原因我无法让它工作。

【问题讨论】:

  • 响应“[objectObject]”,你从哪里得到的?在组件级别还是在视图中?

标签: angular typescript


【解决方案1】:

您可以在服务中使用 Post 方法。

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

【讨论】:

    【解决方案2】:

    你可以尝试这样使用。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-12
      • 2017-01-17
      • 2021-02-19
      • 2019-07-24
      • 2020-03-15
      • 2019-10-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多