[英]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.