2016-07-05 184 views
0

我收到異常'不能讀取屬性'訂閱'的undefined',但我沒有得到它,我做錯了什麼。Angular 2訂閱不工作

checkUserCredentials() { 
    let response; 
    let user = {email: this.email, password: this.password}; 
    this.userService.getUser(user).subscribe((res) => response = res); 
    } 

服務:

getUser(user): any { 
    //this.http.get('http://localhost:3000/users?email = '+user.email+'&password='+user.password, 
    let headers = new Headers(); 
    let postResponse; 
    headers.append('Content-Type', 'application/json'); 
    this.http.post('http://localhost:3000/users', 
     JSON.stringify(user), 
     {headers:headers}) 
     .map((res: Response) => res.json()) 
    } 

回答

4

您需要將getUser方法中返回:

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

但是從我得到的console.log (響應)在方法checkUserCredentials()..任何想法爲什麼? –

+0

您嘗試訂閱您的http請求返回的observable ...不要忘記這樣的調用是異步的,並且您在訂閱時提供回調(這裏是一個箭頭函數)。 –

2

有一個return失蹤。該方法不返回任何內容,爲此它含蓄地返回undefined這會導致錯誤您將獲得:

getUser(user): any { 
    //this.http.get('http://localhost:3000/users?email = '+user.email+'&password='+user.password, 
    let headers = new Headers(); 
    let postResponse; 
    headers.append('Content-Type', 'application/json'); 
    // vvv missing return 
    return this.http.post('http://localhost:3000/users', 
     JSON.stringify(user), 
     {headers:headers}) 
     .map((res: Response) => res.json()) 
    }