[英]Angular2 http.post gets executed twice
我遇到了一個奇怪的問題,Angular2的(RC1)Http服務執行兩次http.post調用。 我調試了我的應用程序,我知道這不是一個點擊事件問題。 所有通往核心服務呼叫的呼叫
public create(json: Object, params?: Object): Observable<T> {
let body = JSON.stringify([json]);
let headers = this.getHeaders();
let options = new RequestOptions({ headers: headers });
return this._http.post(this.createURL(this.getCreateURL(), [], params), body, options)
.map(res => this.handleObjectResponse(res));
}
運行一次。 然后,當我開始跟蹤問題時,我發現我的處理程序this.handleObjectResponse
被執行了兩次。 所以我進一步鑽研並到達@angular/http/src/backends/xhr_backend.ts
他們這樣做了
constructor(req: Request, browserXHR: BrowserXhr, baseResponseOptions?: ResponseOptions) {
this.request = req;
this.response = new Observable<Response>((responseObserver: Observer<Response>) => {
let _xhr: XMLHttpRequest = browserXHR.build();
_xhr.open(RequestMethod[req.method].toUpperCase(), req.url);
// load event handler
...
..
所以我在this.request = req;
上放了一個斷點this.request = req;
然后在let _xhr: XMLHttpRequest = browserXHR.build();
上使用另一個斷點let _xhr: XMLHttpRequest = browserXHR.build();
我發現我擊中了第一個斷點,但后來我從回調中擊中了第二個斷點兩次。
這讓我瘋了,所以我想檢查一下熟悉angular2內部的人是否可以說明這看起來像是一個錯誤或者我做錯了什么。
在我的代碼中,我創建了一些抽象的通用服務類:GenericService和FullService,它擴展了GenericService。 這兩個都是抽象的並且使用泛型,並且在不同組件中注入的實際服務類都擴展了GenericService或FullService。 你們認為這個設置可能是雙重執行后的責任嗎?
所有的想法都很感激!
提前致謝!
PS
這不會發生在獲取,但它也發生在put。
這發生在我身上,因為我在表單的一個輸入字段上有(key.enter)="someSubmitFunction()"
。 當我在此字段上按Enter鍵時,表單將提交兩次。 顯然,這不是必需的。 當我刪除它時,表單仍會在我按Enter鍵時提交,但現在只提交一次。
its happening because HTTP OPTIONS executed first, and you have to restrict unwanted HTTP method before executing your Logic, always use isset method,see example below
if(isset($_POST))
{
$name = $_POST["name"];
$country = $_POST["country"];
$sql = 'INSERT INTO user values("' . $name . '","' . $country . '")';
if ( $conn->query($sql)=== TRUE)
{
$outp = "Inserted " . $name . " and " . $country;
echo json_encode($outp);
} else {
echo json_encode("Error: " . $sql . "<br>" . $conn->error);
}
}
here it will insert row in table only when its POST METHOD.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.