Angular : TypeError: Cannot read property 'length' of null when subscribe()

Angular : TypeError: Cannot read property 'length' of null when subscribe()

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

我如何将用户名存储在 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;
}

由于您在浏览器的网络面板中没有看到请求,看来您没有发送请求。这可能是因为您没有在此行中设置令牌:

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