【发布时间】:2020-10-31 03:53:00
【问题描述】:
我正在观看 MEAN Stack - Angular 2 中的平均身份验证应用教程,因为我是 Angular 新手,并且 我正在使用 Angular 8,由于新的一些代码已被弃用 更新。所以我有这段代码,但我不知道如何修复它。
这是我在 Auth.service.ts 中的工作代码
这段代码没有错误
authenticateUser(user){
let headers = new HttpHeaders();
headers.append('Content-Type','application/json');
return this.http.post('http://localhost:3000/users/authenticate', user,{headers: headers})
}
storeUserData(token, user){
localStorage.setItem('id_token', token);
localStorage.setItem('user', JSON.stringify(user));
this.authToken = token;
this.user = user;
}
logout(){
this.authToken = null;
this.user = null;
localStorage.clear();
}
在我的 login.component.ts 中显示错误
“对象”类型上不存在属性“令牌”
“对象”类型上不存在属性“用户”
“对象”类型上不存在属性“msg”
这是我的 login.component.ts 代码
onLoginSubmit(){
const user = {
username: this.username,
password: this.password
}
this.authService.authenticateUser(user).subscribe(data => {
if(data){
this.authService.storeUserData(data.token, data.user);
this.flashMessage.show('You are now logged in', {
cssClass: 'alert-success',
timeout: 5000});
this.router.navigate(['dashboard']);
} else {
this.flashMessage.show(data.msg, {
cssClass: 'alert-danger',
timeout: 5000});
this.router.navigate(['login']);
}
});
}
login.components.ts 文件如果我输入了错误的登录凭据,那就是 登录。
onLoginSubmit(){
const user = {
username: this.username,
password: this.password
}
this.authService.authenticateUser(user).subscribe(data => {
console.log(data);
if(user){
this.authService.storeUserData(data.token, data.user);
this.flashMessage.show('You are now logged in', {
cssClass: 'alert-success',
timeout: 5000});
this.router.navigate(['dashboard']);
} else {
this.flashMessage.show(data.msg, {
cssClass: 'alert-danger',
timeout: 5000});
this.router.navigate(['login']);
}
});
}
【问题讨论】:
-
你能把 console.log(data) 放在 if(data) 之前吗?并在此处粘贴响应。很容易给出答案。
-
你在 console.log(data) 中看到了什么;
-
{success: false, msg: "User not found"} msg: "User not found" 成功: false
-
我输入了错误的用户名和密码,但是在我的界面中是“登录成功”
-
一次提交必须有一个错误。
标签: angular typescript authentication angular8 mean-stack