2016-07-05 186 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()) 
    }