Angular http 客户端 return 204 http 代码时为 false

Angular http client return false when 204 http code

我用我的 angular 服务发出了一个 http post 请求,我正在等待一个布尔值 return。 但是对于没有内容的 204 http 代码响应,angular return false.

这是我的服务功能:

public create(
        base_price: number,
        domain_id: number|null
    ): Observable<boolean> {
        this.isLoadingSubject.next(true);
        return this.http.post<boolean>(`${API_URL}/pictures`, {
            base_price,
            domain_id
        })
        .pipe(finalize(() => this.isLoadingSubject.next(false)))
    }

还有我的组件:

submit() {
        this.hasError = false;
        const create = this.pictureService
            .create(
                this.f.base_price.value,
                this.f.domain_id.value,
            )
            .pipe(first())
            .subscribe((result: boolean) => {
                this.hasError = !result;
            });
        this.unsubscribe.push(create);
    }

所以 create 函数 return false 并且在我的案例中我没有找到捕获 204 状态的解决方案。

谢谢

如果我们要读取错误状态并且如果它是 204 我们 return 错误怎么办?在我的例子中,我得到的是 404,但你可以将它换成 204。

<div class="card text-center m-3">
    <h5 class="card-header">POST request with error handling</h5>
    <div class="card-body">
        Error message: {{errorMessage}}
        <br>
        I will return boolean: {{returnBool}}
    </div>
</div>
@Component({
  selector: 'post-request-error-handling',
  templateUrl: 'post-request-error-handling.component.html',
})
export class PostRequestErrorHandlingComponent implements OnInit {
  postId;
  errorMessage;
  returnBool: boolean;

  constructor(private http: HttpClient) {}

  ngOnInit() {
    this.http
      .post<any>('https://reqres.in/invalid-url', {
        title: 'Angular POST Request Example',
      })
      .subscribe({
        next: (data) => {
          this.postId = data.id;
        },
        error: (error) => {
          this.errorMessage = error.message;
          console.error('There was an error!', error);
          if (error.status == 404) {
            console.log('Return boolean false');
            this.returnBool = false;
          }
        },
      });
  }
}

这是一个工作示例:https://stackblitz.com/edit/angular-http-post-examples-hpa8pv?file=app%2Fcomponents%2Fpost-request-error-handling.component.ts

您只是想检查响应是否为 204?

如果是这种情况,您只需将 observe: response 添加到选项即可。

this.http.post < boolean > (`${API_URL}/pictures`, {
  base_price,
  domain_id
}, {
  observe: 'response'
})

然后你检查响应状态像

submit() {
        this.hasError = false;
        const create = this.pictureService
            .create(
                this.f.base_price.value,
                this.f.domain_id.value,
            )
            .pipe(first())
            .subscribe(response => {
                if (response.status !== 204) {
                   // Do whatever
                }
            });
        this.unsubscribe.push(create);
    }

HttpClient 文档https://angular.io/guide/http#reading-the-full-response