use*_*113 1 http angular-services angular
在服务中发出 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!!!!!
Run Code Online (Sandbox Code Playgroud)
我在加载组件时订阅了 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!!!!! ");
})
}
}
Run Code Online (Sandbox Code Playgroud)
用户服务:
//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})}
);
}
Run Code Online (Sandbox Code Playgroud)
我如何将用户名存储在 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'});
}
}
Run Code Online (Sandbox Code Playgroud)
知道该方法在后端工作,如这张图片 ,您认为问题是什么?是服务注入问题还是依赖关系,还是其他问题?
编辑 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;
}
Run Code Online (Sandbox Code Playgroud)
由于您没有在浏览器的网络面板中看到请求,因此您似乎没有发送请求。这可能是因为您没有在这一行中设置令牌:
if(this.jwtToken==null) this.authenticationService.loadToken();
Run Code Online (Sandbox Code Playgroud)
错误:
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)
Run Code Online (Sandbox Code Playgroud)
表示,您的 Header ( Authorization
) 是null
,因此无法读取。
尝试将行更改为:
if(this.jwtToken==null) this.jwtToken = this.authenticationService.loadToken();
Run Code Online (Sandbox Code Playgroud)
现在您应该在网络面板中看到您的请求
或者您可能只想检查令牌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})}
);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5736 次 |
最近记录: |