我的前端检查后端以查看访客模型是否存在。此调用使用邮递员(POST
到localhost:1337/visitor/exists
使用数据:{'email': 'some@email.com'}
)。当我尝试让我的angular2服务进行相同的调用时,它会无声地失败。
这是我的服务:
@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);
}
}
为什么我不能从后端得到回复?
我在我的组件中调用它:
constructor(private myService : MyService){
}
...
checkEmailUniqueness(fieldTouched){
if(fieldTouched){
this.myService.checkVisitor(this.visitor.email)
}
}
答案 0 :(得分:6)
默认情况下,Observable对于他们subscribe
需要“冷”,以“触发”它们。
示例:
this.myService.checkVisitor(this.visitor.email).subscribe((response)=>{
console.log(response);
})
答案 1 :(得分:0)
尝试这种方式:
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);
}
}