Angular 2在init上调用API

时间:2016-08-17 15:27:21

标签: angular

我有一个角度服务,我试图调用api来获取基于localStorage ID的用户数据。由于某种原因,API甚至没有被调用。有人可以帮忙吗?我在构造函数中调用getUser()函数...

这是我的代码:

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 个答案:

答案 0 :(得分:2)

如果没有.subscribe(...).toPromise(),可观察者不会做任何事情。

您可以直接在getUser()内进行

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

或你称之为

的地方
  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();
  }

您可能还想对收到的用户信息执行某些操作。目前,除了打​​印到控制台外,接收的数据没有任何变化。