2016-07-05 10 views
0

私は例外を取得 'プロパティを読み取ることができません'の未定義のsubscribe 'しかし私は間違って何をしています。角2の購読doesntの仕事

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()) 
    } 
関連する問題