简体   繁体   English

Angular2 http.post执行两次

[英]Angular2 http.post gets executed twice

I came across a weird issue where the Angular2's (RC1) Http service executes the http.post call twice. 我遇到了一个奇怪的问题,Angular2的(RC1)Http服务执行两次http.post调用。 I've debugged my app and I know for a fact this is not a click event issue. 我调试了我的应用程序,我知道这不是一个点击事件问题。 All the calls that lead up to the core service call 所有通往核心服务呼叫的呼叫

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));
}

are run once. 运行一次。 Then when I started tracing the issue I found out that my handler this.handleObjectResponse gets executed twice. 然后,当我开始跟踪问题时,我发现我的处理程序this.handleObjectResponse被执行了两次。 So I delved further and reached @angular/http/src/backends/xhr_backend.ts where they do this 所以我进一步钻研并到达@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
        ...
        ..

So I put a breakpoint on this.request = req; 所以我在this.request = req;上放了一个断点this.request = req; and then another breakpoint on let _xhr: XMLHttpRequest = browserXHR.build(); 然后在let _xhr: XMLHttpRequest = browserXHR.build();上使用另一个断点let _xhr: XMLHttpRequest = browserXHR.build(); and I found out I hit the first breakpoint once but then I hit the second breakpoint from the callback twice. 我发现我击中了第一个断点,但后来我从回调中击中了第二个断点两次。

This has been driving me nuts so I wanted to check whether anyone familiar with the angular2 internals could shed some light whether this looks like a bug or something that I've done wrong. 这让我疯了,所以我想检查一下熟悉angular2内部的人是否可以说明这看起来像是一个错误或者我做错了什么。

In my code I've created some abstract generic service classes: GenericService and FullService which extends GenericService. 在我的代码中,我创建了一些抽象的通用服务类:GenericService和FullService,它扩展了GenericService。 Both of these are abstract and use generics and the real service classes that get injected in the different components all extend either GenericService or FullService. 这两个都是抽象的并且使用泛型,并且在不同组件中注入的实际服务类都扩展了GenericService或FullService。 Do you guys think this setup could possibly be responsible for the double post executions? 你们认为这个设置可能是双重执行后的责任吗?

All ideas are appreciated! 所有的想法都很感激!

Thanks in advance! 提前致谢!

PS PS

This doesn't happen with gets but it also happens with puts. 这不会发生在获取,但它也发生在put。

The http service returns a cold observable that get executed on every subscribe , you want to convert it to a hot observable that get only executed on the first subscribe and share the same value for subsequent subscribes. http服务返回一个在每个订阅上执行的冷可观察对象,您希望将其转换为仅在第一个订阅时执行的热可观察对象,并为后续订阅共享相同的值。

To convert it all you have to do is share it: 要转换它,您只需分享它:

return this._http.post(this.createURL(this.getCreateURL(), [], params), body, options)
.map(res => this.handleObjectResponse(res))
.share();

This was happening to me because I have (key.enter)="someSubmitFunction()" on one of the input fields of a form. 这发生在我身上,因为我在表单的一个输入字段上有(key.enter)="someSubmitFunction()" When I hit enter on this field the form would submit twice. 当我在此字段上按Enter键时,表单将提交两次。 Apparently, this wasn't needed. 显然,这不是必需的。 When I removed this, the form would still submit when I hit enter, but now only once. 当我删除它时,表单仍会在我按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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM