我正在使用角度4中的现有代码,我正在尝试将其更改为角度5: 在这部分我有一个auth.service.ts,我有错误:
import { Injectable } from '@angular/core';
import {User} from '../model/model.user';
import 'rxjs/add/operator/map';
import {HttpClient, HttpHeaders} from '@angular/common/http';
@Injectable()
export class AuthService {
constructor(public http: HttpClient) { }
public logIn(user: User) {
const headers = new HttpHeaders();
headers.append('Accept', 'application/json')
const base64Credential: string = btoa( user.username + ':' + user.password);
headers.append('Authorization', 'Basic ' + base64Credential);
this.http.get('http://localhost:8081/' + '/account/login', {
headers: headers}).map(resp => {
// login successful if there's a jwt token in the response
// this line where i have a problem :
user = resp.json().principal; // the returned user object is a principal object
if (user) {
// store user details in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
}
});
}
logOut() {
// remove user from local storage to log user out
return this.http.post('http://localhost:8081' + 'logout', {})
.map(resp => {
localStorage.removeItem('currentUser');
});
}
}
如果我有任何改变,请告诉我 实际错误是:
error :src/services/auth.service.ts(19,21): error TS2339: Property 'json' does not exist on type 'Object'.
答案 0 :(得分:1)
您可以将any
类型添加到resp
this.http.get('http://localhost:8081/' + '/account/login', { headers: headers}).map(resp: any =>
{
user = resp.json().principal;
if (user) {
localStorage.setItem('currentUser', JSON.stringify(user));
}
});
答案 1 :(得分:0)
删除地图运算符中的resp.json()
,因为 HttpClient 会为我们处理它。我们不需要再次解析JSON。
public logIn(user: User) {
const headers = new HttpHeaders();
headers.append('Accept', 'application/json')
const base64Credential: string = btoa( user.username + ':' + user.password);
headers.append('Authorization', 'Basic ' + base64Credential);
this.http.get('http://localhost:8081/' + '/account/login', {headers)
.map(resp => {
// this response is already parsed into a JSON by HttpClient. We don't need to do that explicitly
// do something
return resp;
})
...
}
答案 2 :(得分:0)
你可以这样做
this.http.get('http://localhost:8081/' + '/account/login', {
headers: headers}).subscribe(resp => {
user = resp['principal'];
if (user) {
localStorage.setItem('currentUser', JSON.stringify(user));
}
});
希望这个答案能解决你的问题