在服务中发出HTTP请求时,我得到以下响应:
TypeError: Cannot read property 'length' of null
at eval (http.js:123)
at Array.forEach (<anonymous>)
at HttpHeaders.lazyInit (http.js:117)
at HttpHeaders.init (http.js:265)
at HttpHeaders.forEach (http.js:368)
at Observable.eval [as _subscribe] (http.js:2172)
at Observable.subscribe (Observable.js:162)
at eval (subscribeToObservable.js:16)
at subscribeToResult (subscribeToResult.js:6)
at MergeMapSubscriber._innerSub (mergeMap.js:127)
ALERT!!!!!
我在加载组件时订阅了HTTP请求:
export class TasksComponent implements OnInit {
currentUser:any;
username:string=null;
constructor(private usersService:UsersService) {}
ngOnInit() {
this.username=localStorage.getItem('currentUsername');
console.log(this.username);
this.usersService.getUserByUsername(this.username)
.subscribe(data=>{
console.log(data);
this.currentUser=data;
},err=>{
console.log(err);
console.log("ALERT!!!!! ");
})
}
}
UsersService:
//for getting a user by its username
getUserByUsername(username:string){
if(this.jwtToken==null) this.authenticationService.loadToken();
return this.http.get(this.host+"/userByUsername?username="+username
, {headers:new HttpHeaders({'Authorization':this.jwtToken})}
);
}
我如何将用户名存储在localStorage中,以便可以使用它来查找具有其所有属性的用户:
@Injectable()
export class AuthenticationService {
private host:string="http://localhost:8080";
constructor(private http:HttpClient){}
login(user){
localStorage.setItem('currentUsername', user.username);
return this.http.post(this.host+"/login",user, {observe:'response'});
}
}
My localStorage after a Log In
知道该方法在后端工作,就像this picture一样 您认为问题是什么?是服务注入问题,还是有关依赖项的问题?
编辑 loadToken函数:
loadToken(){
this.jwtToken=localStorage.getItem('token');
console.log(this.jwtToken);
let jwtHelper=new JwtHelper();
this.roles=jwtHelper.decodeToken(this.jwtToken).roles;
return this.jwtToken;
}
答案 0 :(得分:2)
由于您没有在浏览器的网络面板中看到该请求,因此似乎没有发送该请求。这可能是因为您没有在这一行中设置令牌:
if(this.jwtToken==null) this.authenticationService.loadToken();
错误:
TypeError: Cannot read property 'length' of null
at eval (http.js:123)
at Array.forEach (<anonymous>)
at HttpHeaders.lazyInit (http.js:117)
at HttpHeaders.init (http.js:265)
at HttpHeaders.forEach (http.js:368)
表示您的标题(Authorization
)为null
,因此无法读取。
尝试将行更改为:
if(this.jwtToken==null) this.jwtToken = this.authenticationService.loadToken();
现在您应该在网络面板中看到您的请求
或者也许您只想检查authenticationService
本身上的令牌:
if(this.authenticationService.jwtToken==null) this.authenticationService.loadToken();
return this.http.get(this.host+"/userByUsername?username="+username
, {headers:new HttpHeaders({'Authorization':this.authenticationService.jwtToken})}
);