Angular2 http post not working silently
My frontend is checking the back end to see if the visitor model exists. This call works using mail manager ( POST
up 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.
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)
}
}
+3
source to share
2 answers
Try this way:
import { Http, Headers, Response, URLSearchParams } from '@angular/http';
@Injectable()
export class MyService {
private myUrl = 'localhost:1337/visitor/exists';
private globalHeaders: Headers = new Headers();
constructor(private http: Http) { }
checkVisitor(email :string): Observable<boolean> {
console.log('in myservice, checkvisitor; email: ', email); // this outputs
let body = {'email': email};
console.log('body, ', body); // this also outputs
return this.http.post(this.myUrl, JSON.stringify(body), {headers: this.globalHeaders})
.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);
}
}
0
source to share