angularangular-httpclientangular-http

Angular http client return false when 204 http code


I made a http post request with my angular service and i'm waiting for a boolean return. But with the 204 http code response with no content, angular return false.

This is my service function :

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)))
    }

And my component :

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);
    }

So the create function return false and i didn't find a solution to catch the 204 status in my case.

Thank you


Solution

  • Are you just trying to check whether the response is 204?

    If that's the case you can just simply just have to add the observe: response to the options.

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

    Then you check the response status like

    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 docs https://angular.io/guide/http#reading-the-full-response