Api post 调用在使用 Angular 4 时不起作用

Api post call is not working in using Angular 4

我在 angular 工作 4 使用网络 api 2 我的 post 呼叫无法正常工作 api。问题是它甚至没有给我一个错误。这是我的代码

 registerUser() {
    this.confirmPasswordMessage = false;
    if (this.registerForm.valid) {
      this.confirmPasswordMessage = false;
         if (this._registerModel.Password.trim() !== this._registerModel.ConfirmPassword.trim()) {
             this.confirmPasswordMessage = true;
             this._progressBar.done();
             return false;
        }
        const _data = JSON.stringify(this._registerModel);
        this._apiService.postCall('Account/Register', _data).subscribe(resp => {
        }, error => () => {
          console.log(error); }, () => {
          });
    } else {
        return false;
    }
  }

这是我的 api 服务代码。

public postCall<T>(apiUrl: any, itemName: any): Observable<T> {
    const _options = { headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + localStorage.getItem('access_token')
      }
    )};
      return this.http.post<T>(this.actionUrl + apiUrl, itemName, _options);
  }

这是我的 json 我路过。当我 运行 这个 json 通过 post 人时,它击中了 api。但我不明白为什么它没有从 angular 应用程序中命中它。

"{"FirstName":"Kamran","LastName":"Khan","Email":"kamrankhan473@gmail.com","UserName":"kamrankhan","Password":"Kamran@786","ConfirmPassword":"Kamran@786"}"

api 没问题,我用 postman 测试过,工作正常。

我看到了多个问题。

  1. 删除if条件中的return false。它 return 来自发出 HTTP 请求之前的函数。
  2. else 块是多余的。无论 if 语句是否为真,该函数都会 return 两种方式。
  3. 删除 JSON.stringify()。您需要发送 JSON,而不是字符串。
  4. 向 URL 添加一个前导斜杠。将 'Account/Register' 替换为 '/Account/Register'.
  5. 错误回调函数定义中的问题。这里 error 是函数的参数。您不能定义 error => () => {}.
  6. 形式的函数
  7. 服务函数中的泛型类型变量<T>是多余的。这里没有使用它。

尝试以下方法

组件

registerUser() {
  this.confirmPasswordMessage = false;
  if (this.registerForm.valid) {
    this.confirmPasswordMessage = false;
    if (this._registerModel.Password.trim() !== this._registerModel.ConfirmPassword.trim()) {
      this.confirmPasswordMessage = true;
      this._progressBar.done();
      // no `return false;` here
    }
    this._apiService.postCall('/Account/Register', this._registerModel).subscribe(
      resp => { console.log(resp); }, 
      error => { console.log(error); }, 
      () => { console.log('complete'); }
    );
  }
}

服务

public postCall(apiUrl: any, itemName: any): Observable<any> {
  const _options = { 
    headers: new HttpHeaders({
      'Content-Type': 'application/json',
      'Authorization': 'Bearer ' + localStorage.getItem('access_token');
    }
  )};
  return this.http.post(this.actionUrl + apiUrl, itemName, _options);
}

如果您从 Angular 开始,我建议您先完成 Angular tutorial。介绍了Angular.

的基本概念