在Angular App / API REST中获取登录令牌时遇到了麻烦 这是我使用的组件和服务。 注册部分工作正常,我什至以正确的类型获得了数据库中所有的intel,但主要问题是登录。 我认为所有进口商品都是正确的。
export class LoginComponent implements OnInit {
loginForm: FormGroup;
username = '';
password = '';
isLoadingResults = false;
constructor(private formBuilder: FormBuilder, private router: Router, private authService:
AuthService) {}
ngOnInit() {
this.loginForm = this.formBuilder.group({
'username': [null, Validators.required],
'password': [null, Validators.required]
});
}
onFormSubmit(form: NgForm) {
this.authService.login(form)
.subscribe(res => {
console.log(res);
if (res.token) {
localStorage.setItem('token', res.token);
this.router.navigate(['ads']);
}
}, (err) => {
console.log(err);
});
}
register() {
this.router.navigate(['register']);
}
}
这是我的授权服务:
const apiUrl = 'http://localhost:9191/';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Allow-Control-Access-Origin': '*'
})
};
@Injectable({
providedIn: 'root'
})
export class AuthService {
isLoggedIn = false;
redirectUrl: string;
constructor(private http: HttpClient) {}
login(data: any): Observable<any> {
return this.http.post<any>(apiUrl + 'login', data, httpOptions)
.pipe(
tap(_ => this.isLoggedIn = true),
catchError(this.handleError('login', []))
);
}
register(data: any): Observable<any> {
return this.http.post<any>(apiUrl + 'users/signup', data, httpOptions)
.pipe(
tap(_ => this.log('login')),
catchError(this.handleError('login', []))
);
}
//handleError and log methods here