【问题标题】:Post Method in Angular 6 not sending dataAngular 6中的发布方法不发送数据
【发布时间】:2018-08-10 10:12:49
【问题描述】:

当我使用 get 进行 api 调用时,当我转换为发布它在参数中给我空值时,它工作得很好。我必须使用 [FromBody] 然后只调用 api 但仍然给我参数值 null。我也处理过 CORS。

 const httpOptions = {
  headers: new HttpHeaders({      
    'Content':"application/json",
    'Content-Type':  'application/json;charset=utf-8',
    //'Content-Type':  'application/x-www-form-urlencoded; charset=UTF-8',
    'Authorization': 'Basic ' + btoa(Username + ":" + Password),        
  }),         
};

 checkLogin(form){        
    var obj = { Business_Email: form["Business_Email"], Business_Password: form["Business_Password"] };        
    return this.http.post(this.API_URL+"/Login/LoginValid", JSON.stringify(obj),httpOptions)


  }

我在 Asp .net C# 中有 Web Api

    [HttpPost]
        [ActionName("LoginValid")]
        [Route("api/Login/LoginValid")]
        public ReturnObject LoginValid([FromBody]string businessMaster)
        {
           //Code
        }

【问题讨论】:

    标签: c# api http-post angular6


    【解决方案1】:

    我有类似的代码可以在 angular 6 上正常工作。

    addEmployee(emp: Employee): Observable<number> {
       return this.http.post(this._baseURL + "/api/employee", emp).pipe(
        map(success => success.status))
       }
    
    
    
    [HttpPost]
            public void Post([FromBody]Employee employee)
            {
                db.Employees.Add(employee);
                db.SaveChanges();
    
            }
    

    【讨论】:

    • 跟标头有关系吗?尽管我们的代码相同,但我的却不工作
    • 只需将 http 声明为构造函数(私有 http: Http){}。删除额外的标头设置。希望它会起作用。
    • 当我更改为我的模型类型时,我正在将字符串作为 web api 上的参数。谢谢我已经工作了好几个小时了。
    【解决方案2】:

    要触发 http.post 方法,您必须在某个地方订阅它。见角apihttps://angular.io/guide/http#making-a-delete-request

    “始终订阅!HttpClient 方法不会开始其 HTTP 请求,直到您对该方法返回的 observable 调用 subscribe()。这适用于所有 HttpClient 方法。”

    【讨论】:

    • 我已经在我的登录组件中订阅了它:this.data.checkLogin(this.loginForm.value) .subscribe()
    猜你喜欢
    • 2016-01-30
    • 1970-01-01
    • 2016-08-29
    • 2019-01-22
    • 2016-04-13
    • 1970-01-01
    • 1970-01-01
    • 2012-05-11
    • 2019-05-04
    相关资源
    最近更新 更多