Friday, 26 May 2017

localStorage Angular 4 not accessible

I'm building a website using angular 4 and nodejs. When I try to log in, node sends the data, to angular, which works fine. Its just that when I attempt the login, data doesn't gets stored in local storage.

Here is the code of auth.services.ts

import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';
import { tokenNotExpired }  from 'angular2-jwt';
import { Router } from '@angular/router';


//import { User } from '../../User';

@Injectable()
export class AuthService {
    authToken: any;
    user: any;

    constructor(private http:Http, private router: Router) {
      console.log("authorization service initialized...");
    }

    signIn(user) {
      let headers = new Headers();
      headers.append('Content-Type', 'application/json');
      return this.http.post('http://localhost:3000/users/login', JSON.stringify(user), {headers: headers})
          .map(res => res.json());
    }

    storeUserData(token, user) {
      console.log("storeuserdata");
      localStorage.setItem('id_token', token);
      localStorage.setItem('user', JSON.stringify(user));
      this.authToken = token;
      this.user = user;
    }

    logout() {
      this.authToken = null;
      this.user = null;
      localStorage.clear();
      this.router.navigateByUrl('/');
    }

    getProfile() {
      let headers = new Headers();
      this.loadToken();
      headers.append('Authorization', this.authToken);
      headers.append('Content-type', 'application/json');
      return this.http.get('http://localhost:3000/users/profile', {headers: headers})
        .map(res => res.json());
    }

    loadToken() {
      this.authToken = localStorage.getItem('id_token');
    }

    loggedIn() {
      return tokenNotExpired();
    }
}

Here is the navbar.component.ts since it contains the login part

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators} from '@angular/forms';
import { Router } from '@angular/router';

import { AuthService } from '../../services/auth.service';
//import { User } from '../../../User';


@Component({
  moduleId: module.id,
  selector: 'navbar',
  templateUrl: `./navbar.component.html`,
})
export class NavBarComponent implements OnInit{
  signInForm: FormGroup;

  constructor(private authService: AuthService, private router: Router) {}

  OnSignIn() {
      const user = {
        email: this.signInForm.value.email,
        password: this.signInForm.value.password
      };
      this.authService.signIn(user)
          .subscribe(
              data => {
                  console.log(data);
                  if (data.success) {
                    this.authService.storeUserData(data.token, data.user);
                    this.router.navigateByUrl('profile');
                  } else {

                  }
              },
              error => console.log(error)
          );
      this.signInForm.reset();
  }

  ngOnInit() {
      this.signInForm = new FormGroup({
        email: new FormControl(null, [
          Validators.required,
          Validators.pattern("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?")
        ]),
        password: new FormControl(null, Validators.required)
      });
  }

  onLogout() {
    this.authService.logout();
  }
}

This is what I receive when I attempt login

Object {success: true, token: "JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyIkX18iO…Tc0fQ.rte25znZW9oASt-6scViAbA37W1DzXxCcg0Z_CMKWTY", user: Object}

and I also get success from the node js part.

When I build this website I was using angular 2. I got busy with my classes and didn't have time to finish it and angular 4 was released. I copied all the code to a fresh directory and made sure that all the node modules are build from start.

Here is my package.json that i had before:

{
  "name": "angular-src",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "^2.4.0",
    "@angular/compiler": "^2.4.0",
    "@angular/core": "^2.4.0",
    "@angular/forms": "^2.4.0",
    "@angular/http": "^2.4.0",
    "@angular/platform-browser": "^2.4.0",
    "@angular/platform-browser-dynamic": "^2.4.0",
    "@angular/router": "^3.4.0",
    "@ng-bootstrap/ng-bootstrap": "^1.0.0-alpha.20",
    "angular2-jwt": "^0.1.28",
    "core-js": "^2.4.1",
    "ng2-uploader": "^2.0.0",
    "ngx-uploader": "^2.2.5",
    "rxjs": "^5.1.0",
    "zone.js": "^0.7.6"
  },
  "devDependencies": {
    "@angular/cli": "^1.0.0",
    "@angular/compiler-cli": "^2.4.0",
    "@types/jasmine": "2.5.38",
    "@types/node": "~6.0.60",
    "codelyzer": "~2.0.0",
    "jasmine-core": "~2.5.2",
    "jasmine-spec-reporter": "~3.2.0",
    "karma": "~1.4.1",
    "karma-chrome-launcher": "~2.0.0",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^0.2.0",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.0",
    "ts-node": "~2.0.0",
    "tslint": "~4.4.2",
    "typescript": "~2.0.0"
  }
}

and this is the new package.json

{
  "name": "angular-src",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.0",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic": "^4.0.0",
    "@angular/router": "^4.0.0",
    "angular2-jwt": "^0.2.3",
    "core-js": "^2.4.1",
    "ngx-uploader": "^3.0.5",
    "rxjs": "^5.1.0",
    "zone.js": "^0.8.4"
  },
  "devDependencies": {
    "@angular/cli": "1.0.6",
    "@angular/compiler-cli": "^4.0.0",
    "@types/jasmine": "2.5.38",
    "@types/node": "~6.0.60",
    "codelyzer": "~2.0.0",
    "jasmine-core": "~2.5.2",
    "jasmine-spec-reporter": "~3.2.0",
    "karma": "~1.4.1",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "karma-coverage-istanbul-reporter": "^0.2.0",
    "protractor": "~5.1.0",
    "ts-node": "~2.0.0",
    "tslint": "~4.5.0",
    "typescript": "~2.2.0"
  }
}

When I run the app with old version of node_modules, it works finne but when I use the new version, user never logs in.

Can someone please help me with this? Thanks



via Hridayam Bakshi

No comments:

Post a Comment