I am new to Angular and for practice i want to make a small application where a user can log in just with his username at first. In order to do so i would like to store the logged in user if the backend returns http status 200. But i can't get the http status of my request. I already looked up several posts here and on other sites, but all those solutions don't seem to work for me.
My Angular Version is: 8.2.14
Here is my login service:
import { Injectable } from '@angular/core';
import {
HttpClient,
HttpHeaders,
HttpErrorResponse,
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
import { User } from '../model/User';
@Injectable({
providedIn: 'root',
})
export class LoginService {
constructor(private http: HttpClient) {}
loginUrl = 'login';
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
}),
};
login(user: User) {
const request = this.http
.post(this.loginUrl, user, this.httpOptions)
.pipe(catchError(this.handleError));
return request;
}
private handleError(error: HttpErrorResponse) {
console.log('handleError Method');
console.log('Errorcode', error.status);
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.error(
`Backend returned code ${error.status}, ` + `body was: ${error.error}`
);
}
// return an observable with a user-facing error message
return throwError('Something bad happened; please try again later.');
}
}
And this is the Login Component calling the service:
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { first } from 'rxjs/operators';
import { LoginService } from 'src/app/services/login.service';
import { User } from '../../../model/User';
@Component({
selector: 'app-login-component',
templateUrl: './login-component.component.html',
styleUrls: ['./login-component.component.css'],
})
export class LoginComponent implements OnInit {
loginForm: FormGroup;
loading = false;
submitted = false;
returnUrl: string;
user: User;
// loginService: LoginService;
constructor(private loginService: LoginService) {}
ngOnInit() {}
login(username: string, password: string) {
const dummyUser = { username, password };
this.loginService.login(dummyUser).subscribe((data) => {
console.log('data', data);
this.user = data;
console.log('user', this.user);
});
}
}
Edit :
With the answer of Mari Mbiru and this post https://stackoverflow.com/a/47761516/12360845 i was able to solve this question. I actually tried to set observe:'response'
before but i didn't put it into httpOptions
but in HttpHeaders
which didn't work. My working post request looks like this now:
login(user: User) {
const request = this.http
.post<User>(
`${this.loginUrl}`,
{ username: user.username, password: user.password },
{
headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
observe: 'response',
}
)
.pipe(catchError(this.handleError));
return request;
}
The HttpClient allows you to view the full response instead of just the body by adding {observe: 'response'}
to your request options. This will return a HttpResponse object that has the body, headers, status, url etc.
So the httpOptions should be:
httpOptions = {
observe:'response'
headers: new HttpHeaders({
'Content-Type': 'application/json',
}),
};
And in the subscription:
this.loginService.login(dummyUser).subscribe((res) => {
console.log('response', res);
this.user = res.body;
console.log('user', this.user);
});
Don't convert the response to JSON then you can find it here
HTTP.post('.....').subscribe( (res) => res['status'], (err) =>.....);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.