Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular2 http post failing silently

Tags:

http

angular

rxjs

My front end checks the back end to see if a visitor model exists. This call works using postman (POST to localhost:1337/visitor/exists with data: {'email': '[email protected]'}). When I try to get my angular2 service to make the same call, it fails silently.

Here is my service:

@Injectable()
export class MyService {
  private myUrl = 'localhost:1337/visitor/exists';

  constructor(private http: Http) { }

  checkVisitor(email :string): Observable<boolean> {
    console.log('in myservice, checkvisitor; email: ', email); // this outputs

    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    let body = {'email': email};

    console.log('body, ', body); // this also outputs

    return this.http.post(this.myUrl, JSON.stringify(body), options)
      .map(this.extractData)
      .catch(this.handleError);

  }

 private extractData(res: Response) {
    console.log('in service, extractData; res: ', res); // this does not print
    let body = res.json();
    return body || { };
  }

 private handleError (error: Response | any) {
    console.log('in handleError'); // this does not print
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
  }
}

Why can't I get a response from my backend?

I am calling this in my component:

constructor(private myService : MyService){
}
...
checkEmailUniqueness(fieldTouched){
    if(fieldTouched){
      this.myService.checkVisitor(this.visitor.email)
    }
  }
like image 641
Jeff Avatar asked Dec 19 '22 08:12

Jeff


1 Answers

Observables are by default "cold" you need to subscribe to them in order to "fire" them.

Example:

this.myService.checkVisitor(this.visitor.email).subscribe((response)=>{
   console.log(response);
})
like image 76
eko Avatar answered Dec 30 '22 08:12

eko