I am trying to implement a simple login system with angular. Currently if I try to login with the correct details I can successfully obtain an access token and store it to local storage.
Attempting to login with wrong details however creates a 401 unauthorised error in response to the post request. Is there another way to test for login failure than looking for parameters in the response like I am doing now?
auth.service.ts
import { Injectable } from '@angular/core';
import { HttpRequest, HttpClient, HttpHeaders, HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
@Injectable()
export class AuthService {
public token: string;
constructor(private http: HttpClient) {
var currentUser = JSON.parse(localStorage.getItem('currentUser'));
this.token = currentUser && currentUser.id;
}
public login(username:string, password:string){
return this.http.post<any>('http://localhost:3000/api/v1/users/login', {username:username, password:password})
.map((res) => {
console.log(res);
let token = res.id ;
let id = res.userId ;
// login successful if there's a jwt token in the response
if (token) {
this.token = token;
// store username and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify({ username: username, token: token, id:id }));
// return true to indicate successful login
return true;
} else {
// return false to indicate failed login
return false;
}
});
}
login-form.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AlertService } from '../../_services/alert.service';
import { AuthService } from '../../_services/auth.service';
@Component({
selector: 'app-login-form',
templateUrl: './login-form.component.html',
styleUrls: ['./login-form.component.css'],
providers: [AuthService, AlertService]
})
export class LoginFormComponent implements OnInit {
model: any = {};
loading = false;
error = '';
returnUrl: string;
constructor(
private router: Router,
private authService: AuthService,
private alertService: AlertService) { }
ngOnInit() {
}
login() {
this.loading = true;
this.authService.login(this.model.username, this.model.password)
.subscribe(result => {
console.log(result);
if (result==true) {
this.loading = false;
//this.router.navigate(['/']);
this.alertService.success('Success', true);
} else {
this.error = 'Username or password is incorrect';
this.loading = false;
}
});
}
}
you can catch a error
Service
return this.http.post<any>('http://localhost:3000/api/v1/users/login', {username:username, password:password})
.map((res) => {
console.log(res);
let token = res.id ;
let id = res.userId ;
// login successful if there's a jwt token in the response
if (token) {
this.token = token;
// store username and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify({ username: username, token: token, id:id }));
// return true to indicate successful login
return true;
} else {
// return false to indicate failed login
return false;
}
}).catch((error: Response) => {
return Observable.throw(error.json());
});
Component
login() {
this.loading = true;
this.authService.login(this.model.username, this.model.password)
.subscribe(result => {
console.log(result);
if (result==true) {
this.loading = false;
//this.router.navigate(['/']);
this.alertService.success('Success', true);
} else {
this.error = 'Username or password is incorrect';
this.loading = false;
}
},(error)=>{
this.error = error.message?error.message:'Username or password is incorrect';
this.loading = false;
}
});
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.