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












1















I'm getting this response when making an HTTP request in service:



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!!!!!


I subscribe the HTTP request when loading my component:



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


How I stored the username in the localStorage so I can use it to find the user with all his properties :



@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



Knowing that the method is working in the back-end like in this picture
what do you think the problem is? is it a service injection problem or is it about dependencies, or another thing?



EDIT
The loadToken function:



loadToken(){
this.jwtToken=localStorage.getItem('token');
console.log(this.jwtToken);
let jwtHelper=new JwtHelper();
this.roles=jwtHelper.decodeToken(this.jwtToken).roles;
return this.jwtToken;
}









share|improve this question

























  • Hmm, hard to say, could be a CORS problem, since your web app is probably hosted at another port(4200). Or maybe loadToken() is asynchronous and you still call the get-request without the auth-token. You should check network requests in your browser and see if you get data from backend on that request...

    – JohnnyAW
    Nov 14 '18 at 23:49













  • it's not a CORS problem because i run other requests(GET,POST,OPTIONS...) and they work fine , i'll add the loadToken() function in the question. and i'v checked Network in my browser and i don't get data from backend.

    – user10497113
    Nov 16 '18 at 11:49











  • what is the HTTP-Code? 200? Btw. empty response is a signal for CORS issue...

    – JohnnyAW
    Nov 16 '18 at 11:51











  • for login link it's 200

    – user10497113
    Nov 16 '18 at 11:52











  • no, for the request, where you have problems

    – JohnnyAW
    Nov 16 '18 at 11:53
















1















I'm getting this response when making an HTTP request in service:



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!!!!!


I subscribe the HTTP request when loading my component:



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


How I stored the username in the localStorage so I can use it to find the user with all his properties :



@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



Knowing that the method is working in the back-end like in this picture
what do you think the problem is? is it a service injection problem or is it about dependencies, or another thing?



EDIT
The loadToken function:



loadToken(){
this.jwtToken=localStorage.getItem('token');
console.log(this.jwtToken);
let jwtHelper=new JwtHelper();
this.roles=jwtHelper.decodeToken(this.jwtToken).roles;
return this.jwtToken;
}









share|improve this question

























  • Hmm, hard to say, could be a CORS problem, since your web app is probably hosted at another port(4200). Or maybe loadToken() is asynchronous and you still call the get-request without the auth-token. You should check network requests in your browser and see if you get data from backend on that request...

    – JohnnyAW
    Nov 14 '18 at 23:49













  • it's not a CORS problem because i run other requests(GET,POST,OPTIONS...) and they work fine , i'll add the loadToken() function in the question. and i'v checked Network in my browser and i don't get data from backend.

    – user10497113
    Nov 16 '18 at 11:49











  • what is the HTTP-Code? 200? Btw. empty response is a signal for CORS issue...

    – JohnnyAW
    Nov 16 '18 at 11:51











  • for login link it's 200

    – user10497113
    Nov 16 '18 at 11:52











  • no, for the request, where you have problems

    – JohnnyAW
    Nov 16 '18 at 11:53














1












1








1








I'm getting this response when making an HTTP request in service:



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!!!!!


I subscribe the HTTP request when loading my component:



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


How I stored the username in the localStorage so I can use it to find the user with all his properties :



@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



Knowing that the method is working in the back-end like in this picture
what do you think the problem is? is it a service injection problem or is it about dependencies, or another thing?



EDIT
The loadToken function:



loadToken(){
this.jwtToken=localStorage.getItem('token');
console.log(this.jwtToken);
let jwtHelper=new JwtHelper();
this.roles=jwtHelper.decodeToken(this.jwtToken).roles;
return this.jwtToken;
}









share|improve this question
















I'm getting this response when making an HTTP request in service:



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!!!!!


I subscribe the HTTP request when loading my component:



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


How I stored the username in the localStorage so I can use it to find the user with all his properties :



@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



Knowing that the method is working in the back-end like in this picture
what do you think the problem is? is it a service injection problem or is it about dependencies, or another thing?



EDIT
The loadToken function:



loadToken(){
this.jwtToken=localStorage.getItem('token');
console.log(this.jwtToken);
let jwtHelper=new JwtHelper();
this.roles=jwtHelper.decodeToken(this.jwtToken).roles;
return this.jwtToken;
}






angular http angular-services






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 16 '18 at 11:51







user10497113

















asked Nov 14 '18 at 23:31









user10497113user10497113

125




125













  • Hmm, hard to say, could be a CORS problem, since your web app is probably hosted at another port(4200). Or maybe loadToken() is asynchronous and you still call the get-request without the auth-token. You should check network requests in your browser and see if you get data from backend on that request...

    – JohnnyAW
    Nov 14 '18 at 23:49













  • it's not a CORS problem because i run other requests(GET,POST,OPTIONS...) and they work fine , i'll add the loadToken() function in the question. and i'v checked Network in my browser and i don't get data from backend.

    – user10497113
    Nov 16 '18 at 11:49











  • what is the HTTP-Code? 200? Btw. empty response is a signal for CORS issue...

    – JohnnyAW
    Nov 16 '18 at 11:51











  • for login link it's 200

    – user10497113
    Nov 16 '18 at 11:52











  • no, for the request, where you have problems

    – JohnnyAW
    Nov 16 '18 at 11:53



















  • Hmm, hard to say, could be a CORS problem, since your web app is probably hosted at another port(4200). Or maybe loadToken() is asynchronous and you still call the get-request without the auth-token. You should check network requests in your browser and see if you get data from backend on that request...

    – JohnnyAW
    Nov 14 '18 at 23:49













  • it's not a CORS problem because i run other requests(GET,POST,OPTIONS...) and they work fine , i'll add the loadToken() function in the question. and i'v checked Network in my browser and i don't get data from backend.

    – user10497113
    Nov 16 '18 at 11:49











  • what is the HTTP-Code? 200? Btw. empty response is a signal for CORS issue...

    – JohnnyAW
    Nov 16 '18 at 11:51











  • for login link it's 200

    – user10497113
    Nov 16 '18 at 11:52











  • no, for the request, where you have problems

    – JohnnyAW
    Nov 16 '18 at 11:53

















Hmm, hard to say, could be a CORS problem, since your web app is probably hosted at another port(4200). Or maybe loadToken() is asynchronous and you still call the get-request without the auth-token. You should check network requests in your browser and see if you get data from backend on that request...

– JohnnyAW
Nov 14 '18 at 23:49







Hmm, hard to say, could be a CORS problem, since your web app is probably hosted at another port(4200). Or maybe loadToken() is asynchronous and you still call the get-request without the auth-token. You should check network requests in your browser and see if you get data from backend on that request...

– JohnnyAW
Nov 14 '18 at 23:49















it's not a CORS problem because i run other requests(GET,POST,OPTIONS...) and they work fine , i'll add the loadToken() function in the question. and i'v checked Network in my browser and i don't get data from backend.

– user10497113
Nov 16 '18 at 11:49





it's not a CORS problem because i run other requests(GET,POST,OPTIONS...) and they work fine , i'll add the loadToken() function in the question. and i'v checked Network in my browser and i don't get data from backend.

– user10497113
Nov 16 '18 at 11:49













what is the HTTP-Code? 200? Btw. empty response is a signal for CORS issue...

– JohnnyAW
Nov 16 '18 at 11:51





what is the HTTP-Code? 200? Btw. empty response is a signal for CORS issue...

– JohnnyAW
Nov 16 '18 at 11:51













for login link it's 200

– user10497113
Nov 16 '18 at 11:52





for login link it's 200

– user10497113
Nov 16 '18 at 11:52













no, for the request, where you have problems

– JohnnyAW
Nov 16 '18 at 11:53





no, for the request, where you have problems

– JohnnyAW
Nov 16 '18 at 11:53












1 Answer
1






active

oldest

votes


















0














since you don't see the request in the network-panel of your browser, it seems that you don't send the request. This is probably because you don't set the token in this line:



if(this.jwtToken==null) this.authenticationService.loadToken();


the error:



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)


indicates, that your Header (Authorization) is null and therefore can't be read.



try to change the line to:



if(this.jwtToken==null) this.jwtToken = this.authenticationService.loadToken();


now you should see your request in the network panel



or maybe you just want to check the token on the authenticationService itself:



if(this.authenticationService.jwtToken==null) this.authenticationService.loadToken();
return this.http.get(this.host+"/userByUsername?username="+username
, {headers:new HttpHeaders({'Authorization':this.authenticationService.jwtToken})}
);





share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53310332%2fangular-typeerror-cannot-read-property-length-of-null-when-subscribe%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    since you don't see the request in the network-panel of your browser, it seems that you don't send the request. This is probably because you don't set the token in this line:



    if(this.jwtToken==null) this.authenticationService.loadToken();


    the error:



    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)


    indicates, that your Header (Authorization) is null and therefore can't be read.



    try to change the line to:



    if(this.jwtToken==null) this.jwtToken = this.authenticationService.loadToken();


    now you should see your request in the network panel



    or maybe you just want to check the token on the authenticationService itself:



    if(this.authenticationService.jwtToken==null) this.authenticationService.loadToken();
    return this.http.get(this.host+"/userByUsername?username="+username
    , {headers:new HttpHeaders({'Authorization':this.authenticationService.jwtToken})}
    );





    share|improve this answer






























      0














      since you don't see the request in the network-panel of your browser, it seems that you don't send the request. This is probably because you don't set the token in this line:



      if(this.jwtToken==null) this.authenticationService.loadToken();


      the error:



      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)


      indicates, that your Header (Authorization) is null and therefore can't be read.



      try to change the line to:



      if(this.jwtToken==null) this.jwtToken = this.authenticationService.loadToken();


      now you should see your request in the network panel



      or maybe you just want to check the token on the authenticationService itself:



      if(this.authenticationService.jwtToken==null) this.authenticationService.loadToken();
      return this.http.get(this.host+"/userByUsername?username="+username
      , {headers:new HttpHeaders({'Authorization':this.authenticationService.jwtToken})}
      );





      share|improve this answer




























        0












        0








        0







        since you don't see the request in the network-panel of your browser, it seems that you don't send the request. This is probably because you don't set the token in this line:



        if(this.jwtToken==null) this.authenticationService.loadToken();


        the error:



        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)


        indicates, that your Header (Authorization) is null and therefore can't be read.



        try to change the line to:



        if(this.jwtToken==null) this.jwtToken = this.authenticationService.loadToken();


        now you should see your request in the network panel



        or maybe you just want to check the token on the authenticationService itself:



        if(this.authenticationService.jwtToken==null) this.authenticationService.loadToken();
        return this.http.get(this.host+"/userByUsername?username="+username
        , {headers:new HttpHeaders({'Authorization':this.authenticationService.jwtToken})}
        );





        share|improve this answer















        since you don't see the request in the network-panel of your browser, it seems that you don't send the request. This is probably because you don't set the token in this line:



        if(this.jwtToken==null) this.authenticationService.loadToken();


        the error:



        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)


        indicates, that your Header (Authorization) is null and therefore can't be read.



        try to change the line to:



        if(this.jwtToken==null) this.jwtToken = this.authenticationService.loadToken();


        now you should see your request in the network panel



        or maybe you just want to check the token on the authenticationService itself:



        if(this.authenticationService.jwtToken==null) this.authenticationService.loadToken();
        return this.http.get(this.host+"/userByUsername?username="+username
        , {headers:new HttpHeaders({'Authorization':this.authenticationService.jwtToken})}
        );






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 16 '18 at 12:09

























        answered Nov 16 '18 at 11:58









        JohnnyAWJohnnyAW

        2,3041923




        2,3041923
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53310332%2fangular-typeerror-cannot-read-property-length-of-null-when-subscribe%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Florida Star v. B. J. F.

            Danny Elfman

            Retrieve a Users Dashboard in Tumblr with R and TumblR. Oauth Issues