Search code examples
angularrxjshttpclientasp-net-core-spa-services

http.post returns res.headers undefined


in my web API (asp core) when I post object to save in DB it return CreatAtRoute wich is the URL or location of the object like: http://localhost:api/photo/45

and it just return "res.headers undefined"

I am using this code to get url of object that recently saved in db

 addBankCard(bankCard: BankCard, id: string): Observable<BankCard> {
    return this.http.post(this.baseUrl + 'users/' + id + '/bankcards', bankCard)
      .pipe(
        flatMap((res) => {
          const loc = (res as Response).headers.get('Location');
          return this.http.get<BankCard>(loc);
        })
      );
  }

and it just returns "res.headers undefined"

the API work perfectly and I am using AllowAnyHeaders in startup class in Aspnetcore webapi

what should I do?


Solution

  • Angular httpclient return response body by default. If you can to access the entire response you need to change observe type in function params :

    addBankCard(bankCard: BankCard, id: string): Observable<BankCard> {
        return this.http.post(this.baseUrl + 'users/' + id + '/bankcards', bankCard,  {observe: 'response'})
          .pipe(
            flatMap((res) => {
              const loc = res.headers.get('Location');
              return this.http.get<BankCard>(loc);
            })
          );
      }