无法访问Angular 5和ASP.NET Core中的statusCode

时间:2018-04-24 12:46:52

标签: c# angular asp.net-core

我有一个服务,它对Core中的操作发出POST请求:

this.http.post(url, loginModel).subscribe(result => {
      console.log(result);
      if (result.statusCode === 200) { // here I got typescript error that `statusCode` does not belong to Object
        this.route.navigateByUrl("/main");
      }
});

和MVC行动:

public class AccountController : Controller
{
        [HttpPost]
        public IActionResult Login([FromBody] LoginViewModel model)
        {
            return Json(Ok());
        }
}

我在控制台中得到的回应是:

{statusCode: 200}

如何修复打字稿错误?我该怎么办?

错误如下:

  错误在... / login / login.service.ts(21,20):错误TS2339:属性   “statusCode”在“对象”类型上不存在。

3 个答案:

答案 0 :(得分:1)

默认情况下,您的$('#pesquisarServicos').click(function (e) { e.preventDefault(); var parametro = document.getElementById('pesquisarServico').value; $.get("http://localhost:8080/service/list/"+parametro) .done(function (data) { var idServico, dataEntradaServico, dataSaidaServico, cpfPessoa, idStatus, descricaoServico; var tabela = "<tr> <td>idServico</td> <td>dataEntradaServico</td> <td>dataSaidaServico</td>" + "<td>cpfPessoa</td> <td>idStatus</td> <td>descricaoServico</td> </tr>" for (var i in data) { idServico = data[i]["idServico"]; dataEntradaServico = data[i]["dataEntradaServico"]; dataSaidaServico = data[i]["dataSaidaServico"]; cpfPessoa = data[i]["cpfPessoa"]; idStatus = data[i]["idStatus"]; descricaoServico = data[i]["descricaoServico"]; tabelaResultado.innerHTML += tabela.replace("idServico", idServico).replace("dataEntradaServico", dataEntradaServico) .replace("dataSaidaServico", dataSaidaServico).replace("cpfPessoa", cpfPessoa).replace("idStatus", idStatus) .replace("descricaoServico", descricaoServico); } }); }); 返回http,以便更好地控制,强力投射如下:

observable<Object>

对于更复杂的API答案:

this.http.post<{statusCode:number}>(url, loginModel).subscribe(result => {
      console.log(result);
      if (result.statusCode === 200) { // here is available
        this.route.navigateByUrl("/main");
      }
});

答案 1 :(得分:1)

使用 HttpClient 时,我也遇到了同样的问题。发生这种情况是因为 httpClient 返回Observable<Object>以绕过此问题我以这种方式使用它,

this.http.post<any>(url, loginModel)
    .subscribe(result => {
         console.log(result);
         if (result.statusCode === 200) {
           this.route.navigateByUrl("/main");
         }
});

答案 2 :(得分:-1)

我假设您需要先以JSON格式解析响应,然后订阅它,以便您可以在方法调用中使用result.statusCode

所以使用此代码:

this.http.post(url, loginModel)
  .map(data => data.json())
  .subscribe(result => {
    console.log(result);
    if (result && result.statusCode === 200) { // here I got typescript error that `statusCode` does not belong to Object
      this.route.navigateByUrl("/main");
    }
});