由于我是Angular的新手,所以我正在Angular 2中观看MEAN Stack-Mean Auth App教程 我正在使用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']);
}
});
}
答案 0 :(得分:1)
我认为您是在谈论打字稿错误:http.post
返回一个Observable<object>
,所以data
是一个object
,并且没有属性token
, user
,msg
在对象中。
根据您告诉我们的信息,您的authenticate
WS应该返回:
interface SuccessResponse {
token: string;
user: any; // should change any to your user type
}
interface FailureResponse {
success: false;
msg: string;
}
type AuthResponse = SuccessResponse | FailureResponse;
authenticateUser(user): Observable<AuthResponse> {
// header for content-type is not needed
return this.http.post<AuthResponse>('http://localhost:3000/users/authenticate', user);
}
您可以像这样使用它:
onLoginSubmit() {
const user = {
username: this.username,
password: this.password
}
this.authService.authenticateUser(user).subscribe(response => {
console.log(data);
if ('token' in response) {
// response is SuccessResponse
this.authService.storeUserData(response.token, response.user);
this.flashMessage.show('You are now logged in', {
cssClass: 'alert-success',
timeout: 5000});
this.router.navigate(['dashboard']);
} else {
// response is FailureResponse
this.flashMessage.show(response.msg, {
cssClass: 'alert-danger',
timeout: 5000});
this.router.navigate(['login']);
}
});
}
那应该对您有用。但是,标准是登录失败时应返回错误(例如代码401),而不是success: false
的OK状态(200)。在这种情况下,代码将有所不同