我正在尝试为我的应用发布一个帖子请求并且它无效,我尝试了多种方法。我没有看到在chrome中的网络选项卡下触发请求。不确定是什么问题,任何帮助表示赞赏。
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
@Injectable()
export class UserService{
private _url="users";
constructor(private _http: Http){
}
checkIfUsernameExists(username){
return this._http.get(this._url+"/"+username)
.map(response => response.json())
}
createUser(user){
let headers = new Headers();
headers.append('Content-Type', 'application/json')
console.log(JSON.stringify(user));
return this._http.post(this._url, JSON.stringify(user),{headers: headers})
.map(response => response.json())
}
}
答案 0 :(得分:1)
首先,您需要捕获 错误并解决错误:
this._http.post(this._url, JSON.stringify(user),{headers: headers})
.subscribe(
(res) => {
// on success
},
(err) => {
// on error
console.error(err);
}
答案 1 :(得分:0)
尝试这样调用它,以便您可以跟踪错误
let headers = new Headers({ 'Content-Type', 'application/json' });
let options = new RequestOptions({ headers: headers });
this.http.post(this._url, JSON.stringify(user),{headers: headers})
.toPromise()
.then( (res: Response) => {
let body = res.json();
this.authService.fillAuthDataFromLogin(body);
this.router.navigate(['/Home']);
return body.data || {};
})
.catch(this.handleError);
此方法中的处理错误
private handleError(error: any) {
////debugger;
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
答案 2 :(得分:0)
使用promise
调用服务 this.UserService.createuser(user)
.subscribe(
data => { this.responseModel= data },
error => console.log('error'),
() => this.getComplete() //complete function
);