2016-11-22 52 views
1

我需要從其他函數中獲取postKey和postValue,它會發送 的密鑰名和密鑰值,然後發佈它。 但我不能找到一種方法來發送字符串化增值經銷商,而不是靜態值Angular2,HTTP post,發送動態json

這樣它不工作:

postRequest(postKey?: any, postValue? any){ 
    return this._http.post(this._url, JSON.stringify({postKey: PostValue })) 
     .map(res => res.json()); 
} 

只喜歡這工作(靜態):

postRequest(post?: any){ 
     return this._http.post(this._url, JSON.stringify({SomeKey: 'SomeValue' })) 
      .map(res => res.json()); 
    } 

回答

2

它可以通過使用達到ES6 feature

postRequest(postKey?: any, postValue){ 
    return this._http.post(this._url, postKey ? JSON.stringify({[postKey]: PostValue }: null)) 
     .map(res => res.json()); 
} 
+0

我收到錯誤: 參數類型的 '{}' 是不能分配給類型的參數「(字符串|數)[]'。 '{}'類型中缺少屬性'find'。 ERROR in [default] C:\ Users \ shay \ Desktop \ Angular2 \ cloud \ src \ app \ http_request.service.ts:54:91 ':'expected。 –

+0

@ShayBinyat嘗試'null'而不是'{}' –

+0

仍然不好 - 它想要在[默認] C:\ Users \ shay \ Desktop \ Angular2 \ cloud \ src \ app \ http_request中出現空錯誤之前的「,」。 service.ts:57:104 ','預計。 ERROR in [default] C:\ Users \ shay \ Desktop \ Angular2 \ cloud \ src \ app \ http_request.service.ts:57:112 ':'expected。 –

0

解決它像th是:

return this._http.post(this._url, '{"' + postKey + '": "' + postValue + '"}')