2
我有一個角度服務,我試圖調用一個API來獲取基於localStorage ID的用戶數據。由於某種原因,API甚至沒有被調用。有人可以幫忙嗎?我調用的getUser()函數的構造函數...Angular 2調用初始化API
這裏是我的代碼:
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);
}
}
我似乎遇到了一個問題,頭文件沒有被添加到.get請求中?我得到一個「toString」解析錯誤 –
請張貼確切的錯誤消息。 –
'{headers}'應該是'{headers:headers}' –