Home > Software design >  Why can't I map a boolean response from http request in Angular?
Why can't I map a boolean response from http request in Angular?

Time:05-14

I am calling a .Net method in my WebAPI from Angular, which sends a boolean to switch something off and returns a boolean with the current status. However when trying to map the response in Angular it is returning undefined. (.Net 6, Angular 13)

.Net Controller:

[HttpPost("/api/Gpio/DisableOutputs")]
public Task<bool> DisableOutputs([FromBody] bool disableOutputs)
{
    var isDisabled = this._gpioService.DisableOutputs(disableOutputs);
    Console.WriteLine(isDisabled);
    return Task.FromResult(isDisabled);
}

In the dev tools in Chrome, I see the response coming through, however I can't map this back to my Angular app.

http response

Angular Service:

disableOutputs(disableOutputs: boolean): Observable<boolean> {
    return from(
      this.authService.getAccessToken()
      .then(token => {
        const headers = new HttpHeaders().set("Authorization", `Bearer ${token}`);
        this.http.post(this.createCompleteRoute("api/Gpio/DisableOutputs", this.envUrl.urlAddress),
          disableOutputs,
          { headers: headers, withCredentials: true }).toPromise();
      })).pipe(map((s: any) => { 
       // 's' is 'undefined' 
      return s as boolean;
    }));
  }

Angular Component:

  disableOutputs() {
    this.service.disableOutputs(!this.outputsDisabled).subscribe(d => {
      this.outputsDisabled = d;
      console.log(d);  
     // 'd' is 'undefined'
    });
  }

CodePudding user response:

You are getting undefined because you are not returning the nested http promise.

But you can simplify your implementation quite a bit using a high-order mapping operator like concatMap, switchMap,...

Itd be something like this.

return from(this.authService.getAccessToken()).pipe(
  concatMap(token => {
    const headers = new HttpHeaders().set("Authorization", `Bearer ${token}`);
    return this.http.post<boolean>(
      this.createCompleteRoute("api/Gpio/DisableOutputs", this.envUrl.urlAddress),
      disableOutputs,
      { headers: headers, withCredentials: true }
    );
 })

Cheers

  • Related