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': 'some@email.com'}
). 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)
}
}
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);
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With