[英]How do I access json key in Angular 4.3 with the new HttpClient?
我正在尝试从Angular 4.0迁移到4.3,以便可以逐步升级到Angular 5或6。
我开发了一个简单的身份验证,将jwt
用于每个请求。 jwt
存储在本地存储中。
我只知道4.3版本现在使用HttpClientModule
,它将被声明为
app.module.ts
import { HttpClientModule } from '@angular/common/http';
imports: [
HttpClientModule,
]
我正在使用服务进行身份验证,注册用户和加载令牌。
验证服务
import { Injectable } from '@angular/core';
//import { Headers } from '@angular/http';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import 'rxjs/add/operator/map';
@Injectable()
export class AuthService {
authToken: any; // class property so we can access it anywhere
user: any;
constructor(private http:HttpClient) { }
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) {
// code for storing user data
}
logout() {
this.authToken = null;
this.user = null;
localStorage.clear();
}
}
login.component.ts
import { AuthService } from 'app/services/auth.service';
@Component({
})
export class LoginComponent implements OnInit {
username: String;
password: String;
constructor(
private _flashMessagesService: FlashMessagesService,
private authService: AuthService,
private router: Router
) { }
ngOnInit() {
}
onLoginSubmit() {
const user = {
username: this.username,
password: this.password
}
this.authService.authenticateUser(user).subscribe(data => {
// console.log(data);
if(data.success) {
this.authService.storeUserData(data.token, data.user);
this.router.navigate(['admin']); //redirect
} else {
this.router.navigate(['login']); //redirect
}
});
}
}
在login.component.ts文件中出现上述错误提示我。
login.component.ts(43,15):类型“对象”上不存在属性“成功”。
我试图在控制台中打印data
,这是我看到的:
{success: true, token: "JWT dlskdlskdlskdlsdklgfdg;kfd;gkd;432ks;dfks;fks;fkds;f", user: {…}}
success: true
token:"JWT dlskdlskdlskdlsdklgfdg;kfd;gkd;432ks;dfks;fks;fkds;f"
user:{id: "95430590435934fkdlkfldskfds", name: "Carlo K", username: "carlok", email: "carlok@gmail.com"}
您知道如何从上面的console.log访问data
吗?
我想在login.component.ts中使用这样的data
:
if(data.success) {
// do code
}
任何想法表示赞赏。 谢谢
Note
:如果我在app.module.ts和Http
Object中使用Angular 4.0- HttpModule
,则不会遇到以上错误
新的HttpClientModule
希望您为http调用提供return type / interface
。 没有type
指定的任何调用将被强制转换为Object
。 就是说,要解决您的问题,可以采用以下方法之一,首选方法3(最佳实践)。
提供any
类型,将此行从return this.http.post(...)
更改为return this.http.post<any>(...)
。
提供any
类型,将此行从this.authService.authenticateUser(user).subscribe(data => ...
更改为this.authService.authenticateUser(user).subscribe(data: any => ...
强类型。 例如。 创建一个界面并使用它。 interface Data { success: boolean; token: string; user: any; }
interface Data { success: boolean; token: string; user: any; }
。 将此行从return this.http.post(...)
更改为return this.http.post<any>(...)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.