我正在尝试使用angular实现一个简单的登录系统。目前,如果我尝试使用正确的详细信息登录,我可以成功获取访问令牌并将其存储到本地存储。
尝试使用错误的详细信息登录会产生401未经授权的错误以响应发布请求。是否有另一种方法来测试登录失败,而不是像我现在一样在响应中查找参数?
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;
}
});
}
登录-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;
}
});
}
}
答案 0 :(得分:1)
你可以发现错误
<强>服务强>
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());
});
<强>组件强>
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;
}
});