2

I have a service in angular that I a trying to call an api to get user data based on localStorage ID. For some reason the API is not even getting called. Can someone help please? I am calling the getUser() function in the constructor...

Here is my code:

import { Injectable, OnInit } from '@angular/core';
import { Router }      from '@angular/router';
import { Http, Headers } from '@angular/http';
import {Subject} from "../../node_modules/rxjs/src/Subject";
import {Observable} from "../../node_modules/rxjs/src/Observable";
import {AuthService} from "./auth.service";


@Injectable()
export class UserService{

  userData:any;
  user:Subject<any>;
  user$:Observable<any>;
  loggedIn = new Subject<boolean>();
  loggedIn$:Observable<any>;


  constructor(private http:Http, public authService:AuthService, public router:Router) {

    this.user = new Subject();
    this.user$ = this.user.asObservable();
    this.loggedIn = new Subject();
    this.loggedIn$ = this.loggedIn.asObservable();
    this.getUser().subscribe();




  }

  getUser(){

if(localStorage['_id'] && localStorage['jwt']){

  let headers = new Headers();
  //headers.append('Content-Type', 'application/json');

  headers.append('x-access-token', localStorage['jwt']);
  console.log('We have a user ID! Lets try to get a user!');
  return this.http
    .get('/api/accounts/' + localStorage['_id'], {headers : headers} )
    .map(res => res.json())
    .map((res) => {
      return res;
    }, (error) => console.log('There was an error', error));
}

}

  }

  createAccount(user) {
    user.assessment = {

      1: {id: "1", answer: "", subs: []},
      2: {id: "2", answer: "", subs: []},
      3: {id: "3", answer: "", subs: []},
      4: {id: "4", answer: "", subs: []},
      5: {id: "5", answer: "", subs: []},
      6: {id: "6", answer: "", subs: []},
      7: {id: "7", answer: "", subs: []},
      8: {id: "8", answer: "", subs: []},
      9: {id: "9", answer: "", subs: []},
      10: {id: "10", answer: "", subs: []},
      11: {id: "11", answer: "", subs: []},
      12: {id: "12", answer: "", subs: []},
      13: {id: "13", answer: "", subs: []},
      14: {id: "14", answer: "", subs: []},
      15: {id: "15", answer: "", subs: []}

    };
    console.log('Attempting to create an account with', user);
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    return this.http
      .post(
        '/api/accounts',
        JSON.stringify(user),
        {headers}
      )
      .map(res => res.json())
      .map((res) => {
        if (res['account']) {
          this.loggedIn.next(true);
          this.userData = res["account"];
          //this.user$ = res;
          //this.user.next('test');
          return res;
        }
      });
  }

  login(user) {

    console.log('Loggin you in...');
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    return this.http
      .post(
        '/api/authenticate',
        JSON.stringify(user),
        {headers}
      )
      .map(res => res.json())
      .map((res) => {
        console.log('Login Result:', res);

          localStorage.setItem('jwt', res.token);
          localStorage.setItem('_id', res.user[0]._id);
          //set user service info...
          this.loggedIn.next(true);
          this.userData = res.user[0];
          this.user.next(res.user[0]);
          return res;
      });
  }


  logout() {
    localStorage.removeItem('jwt');
    this.loggedIn.next(false);
  }

}

1 Answer 1

2

Observables don't do anything without .subscribe(...) or .toPromise().

Either you do it directly inside getUser() like

 getUser(){

    if(localStorage['_id'] && localStorage['jwt']){

      let headers = new Headers();
      headers.append('Content-Type', 'application/json');

      console.log('We have a user ID! Lets try to get a user!');
      this.http
        .get('/api/accounts/' + localStorage['_id'], {headers} )
        .map(res => res.json())
        .subscribe((res) => {
          console.log('User restrieved!', res);
        }, (error) => console.log('There was an error', error));
    }
}

or where you call it

  constructor(private http:Http, public authService:AuthService, public router:Router) {

    this.user = new Subject();
    this.user$ = this.user.asObservable();
    this.loggedIn = new Subject();
    this.loggedIn$ = this.loggedIn.asObservable();
    this.getUser().subscribe();
  }

You probably also want to do something with the received user info. Currently there is nothing happening with the received data except being printed to the console.

Sign up to request clarification or add additional context in comments.

8 Comments

I seem to be having a problem where the headers are not getting added to the .get request? Im getting a "toString" parse error
` {headers}` should be ` {headers: headers}`
Tried that. No luck... here is the URL so you can see the error. tfl.judsondesigns.com
The link seems not to work for me. I see only "Loading ..." on an otherwise entirely white page.
@GünterZöchbauer with es6 you can write '{headers}' instead of '{headers: headers}' if your variable has the same name as the object property you're setting.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.