angularhttpangular-http

Angular get body from HttpEvent<>


I'm performing a get request by calling this method of class AuthService:

 return this.http.post<any>('url',{
    "username": username,
    "password":password
}, this.httpOptions).pipe(catchError(this.errorHandler));

from another class:

this.authService.login(this.username,this.password).subscribe(response =>{
       console.log("Response " + response.token);
    });

The problem here is that property token does not exist in type HttpEvent<any>. If I run it and try to print it anyway, it prints correctly, but the error in code remains. I've tried changing type any to a custom interface with fields representing my response, but the error is the same because it's always HttpEvent.
How can I solve this?


Solution

  • try this

    this.authService.login(this.username,this.password).subscribe((response : any) =>{
           console.log("Response " + response.token);
        });
    

    or if you want to make it typed

    return this.http.post<{token: string}>('url',{
    

    and then

    this.authService.login(this.username,this.password).subscribe((response : {token: string}) =>{
           console.log("Response " + response.token);
        });