[英]Angular HTTP GET/POST does nothing
I'm using the same code to get/post to my API as I did with my previous applications, but now it doesn't work: 我使用与以前的应用程序相同的代码来获取/发布到我的API,但是现在不起作用:
let options_ = {
method: "get",
headers: new Headers({
"Content-Type": "application/json",
"Accept": "application/json"
})
};
return this.http.get(url_, options_).flatMap((response_) => {
return this.processResponse(response_);
})
this code works for me in other applications but in this one doesn't. 此代码在其他应用程序中对我有效,但在本应用程序中无效。 It doesn't reach the server and in the traffic tab I see no request.
它没有到达服务器,并且在“流量”标签中我没有看到任何请求。 I've enabled cors on the server.
我已经在服务器上启用了cors。 How do I fix this issue?
如何解决此问题?
A request isn't executed unless you subscribe
to the Observable
returned by the get
function, as shown in the example below: 除非您
subscribe
由get
函数返回的Observable
否则不会执行请求,如以下示例所示:
doGet() {
return this.http.get(url_, options_).flatMap((response_) => {
return this.processResponse(response_);
});
}
yourOtherFunction() {
doGet().subscribe(result => {
// your code
});
}
Try by using observables fucntions 尝试使用可观察的功能
Get Method 获取方法
getFuntion(): Observable<any[]> {
return this._http.get(this._baseUrl+'/controller/api')
.map(res => {
return res.json().map(item => {
return item;
});
});
}
Post Method 过帐方法
postFunction(id, action) {
let data = {
id: id,
action: action
};
let body = JSON.stringify(data)
let head = new Headers({
'Content-Type': 'application/json'
});
return new Observable(observer => {
this._http.post(this._baseUrl+'/controller/api/',
body , {headers : head})
.map((res: Response) => res.json())
.subscribe(res => {
observer.next(res);
observer.complete();
});
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.