我在服务中发出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!!!!! ");
      })
  }
}

用户服务:
//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})}
    );
}

如何将用户名存储在本地存储中,以便使用它查找具有所有属性的用户:
@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;
}

最佳答案

因为您在浏览器的网络面板中看不到请求,所以似乎您没有发送请求。这可能是因为您没有在此行中设置标记:

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})}
);

10-07 14:56