簡體   English   中英

http.post在Angular 5中不起作用

[英]http.post not working in Angular 5

我正在Angular 5中開發一個應用程序。

http.get服務在這里工作正常,但在http.post出現問題。

下面是我的代碼:

GetEmployee() {
    //Data needs to be grouped in an object array as payload
    var payload = { "StaffCode": this.employeeCode };
    this.showLoader = true;
    this.http.post<StaffInfo>(this.baseURL + 'api/StaffDetail/GetEmployee', JSON.stringify(payload)).subscribe(result => {
        this.Staff = result;
        this.showLoader = false;
    }, error => console.error(error));
}

.net核心中的API:

 [HttpPost("[action]")]
    public Employee GetEmployee(string StaffCode)
    {
        return util.GetEmployee(StaffCode);
    }

我稱它為單擊按鈕

<button type="button" (click)="GetEmployee()" class="btn btn-sm btn-warning">Get Detail</button>

但在我的API中,它為null。

在此處輸入圖片說明

我以錯誤的方式調用post API嗎?

還有一件事,如果我在參數簽名之前添加[FromBody] ,甚至沒有擊中API。

客戶端正在發送復雜的對象模型,但操作需要簡單的字符串。

創建模型以匹配客戶端的有效負載。

public class GetEmployeeModel {
    public string StaffCode { get; set; }
}

更新操作以期望帖子正文中的有效負載。

[HttpPost("[action]")]
public Employee GetEmployee([Frombody]GetEmployeeModel model) {
    return util.GetEmployee(model.StaffCode);
}

還要確保有效負載在客戶端上正確構造並以正確的內容類型發送

var payload = { StaffCode: this.employeeCode };
var json = JSON.stringify(payload);
var url = this.baseURL + 'api/StaffDetail/GetEmployee';
const httpOptions = {
    headers: new HttpHeaders({
        'Content-Type':  'application/json'
    })
};
this.http.post<StaffInfo>(url, json, httpOptions).subscribe(result => {
    this.Staff = result;
    this.showLoader = false;
}, error => console.error(error));

現在,理想情況下,給定操作的名稱和預期的功能,您最好將操作重構為HTTP GET請求,並在路由中傳遞代碼

[HttpGet("[action]/{StaffCode}")]
public Employee GetEmployee(string StaffCode)
{
    return util.GetEmployee(StaffCode);
}

並相應地更新客戶端以向

var url = this.baseURL + 'api/StaffDetail/GetEmployee/' + this.employeeCode;
this.http.get<StaffInfo>(url).subscribe(result => {
    this.Staff = result;
    this.showLoader = false;
}, error => console.error(error));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM