subscribe function always going on error observer

Published

I am following a course on Udemy which uses Angular 2.0 and I’m trying to build it using the latest version. My problem occurs in this function :

checkSession() {
const url = 'http://localhost:8181/checkSession';
const xToken = localStorage.getItem('xAuthToken');
const basicHeader = 'Basic ' + localStorage.getItem('credentials');
const headers = new HttpHeaders({
  'x-auth-token' : JSON.stringify(xToken),
  'Authorization' : basicHeader
});
console.log(url);
console.log(headers);
return this.http.get(url, {headers: headers});

because when I access it on this function:

ngOnInit() {
const xToken = JSON.stringify(localStorage.getItem('xAuthToken'));
if (xToken) {
  this.loginService.checkSession().subscribe(
    res => {
      console.log("Good")
      this.loggedIn = true;
    },
    error => {
      console.log("error = " + error)
      this.loggedIn = false;
    }
  );
}

it always going on the error observer throwing this error:

[object Object]

OnSubmit function:
    onSubmit() {
    this.loginService
      .sendCredential(this.credential.username, this.credential.password)
      .subscribe(
        res => {
          localStorage.setItem('xAuthToken', JSON.stringify(res));
          this.loggedIn = true;
          const encodedCredentials = btoa(this.credential.username + ':' + this.credential.password);
          localStorage.setItem('credentials', encodedCredentials);
          // location.reload();
        },
        error => {
          console.log(error);
        }
      );

Original functions from the course:

checkSession() {
let url = "http://localhost:8181/checkSession";

let headers = new Headers ({
  'x-auth-token' : localStorage.getItem('xAuthToken')
});

return this.http.get(url, {headers: headers});

ngOnInit() {
this.loginService.checkSession().subscribe(
    res => {
        this.loggedIn=true;
    },
    error => {
        this.loggedIn=false;
    }
);

onSubmit() {
this.loginService.sendCredential(this.credential.username, this.credential.password).subscribe(
    res => {
        console.log(res);
        localStorage.setItem("xAuthToken", res.json().token);
        this.loggedIn = true;
        // location.reload();
    },
    error => {
        console.log(error);
    }
);

Because of this error, I cannot save the session. The login works like a charm, but for some reason unknown by me, the session is not saved properly.

Network tab:
Network screenshot 1

Token

Error

checkSession

Source: AngularJS Questions

Published
Categorized as angular, angularjs, javascript, typescript Tagged , , ,

Answers

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Still Have Questions?


Our dedicated development team is here for you!

We can help you find answers to your question for as low as 5$.

Contact Us
faq