Akin Dönmez
Akin Dönmez

Reputation: 363

Angular 2 subscribe doesnt work

i m getting exception 'Cannot read property 'subscribe' of undefined'but i dont get it what am i doing wrong.

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

Service :

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

Upvotes: 0

Views: 106

Answers (2)

Thierry Templier
Thierry Templier

Reputation: 202138

You need to return within the getUser method:

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

Upvotes: 4

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657058

There is a return missing. The method doesn't return anything, therefor it implicitly returns undefined which results in the error you get:

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

Upvotes: 2

Related Questions