Home > Enterprise >  Error when retrieving data from HttpResponse.body in a pipe map
Error when retrieving data from HttpResponse.body in a pipe map

Time:11-11

I have an Angular web application with a service to authenticate users with is called from the User login page. It has some actions done in a pipe(map{}):

login(username, password) {

    return this.http.post<HttpResponse<User>>(`${environment.apiEndPoint}/users/authenticate`, { 
        username, password }, {observe: 'response'})
    .pipe(map(resp => {
        var u: User;
        u = resp.body;
        // do stuff
        localStorage.setItem('currentUser', JSON.stringify(u));
        return u;
    }));
}

Recently I have changed the headers to {observe: 'response'} in order to access the headers but I have found a problem, although I have verified in the Chrome tools that the post response is in resp.body, the compiler is throwing me this error:

error TS2740: Type 'HttpResponse<User>' is missing the following properties from type 'User': id, username, password, firstname, and 5 more.

I have found that if I change u = resp.body; with u = resp.body.body; the error disappears but then at run time it turns out that resp.body.body is undefined while resp.body contains the message.

How can this issue be fixed?

CodePudding user response:

Try the following, don't think you need to specify the HttpResponse type

return this.http.post<User>(...)

CodePudding user response:

I found a solution to this by stringifying and then parsing the body, that is, replacing this line:

u = resp.body;

with these:

 let x = JSON.stringify(resp.body);
 u = JSON.parse(x);
  • Related