Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

http.put request is executed twice in Angular2

Tags:

angular

I am trying to update a company record calling an API from my Angular2 application. I noticed while debugging that the http call is being executed twice. I found another stackoverflow thread that is identical to this and the answer was to add .share() due to hot and cold Observables. I have added this to my http call but this did not resolve the issue. I appreciate any assistance!

enter image description here

company.service.ts

update(company: Company): Observable<Company> {
    return this._http.put(URL_COMPANY, JSON.stringify(company), { headers: this.headers })
        .map((res: Response) => company).share();
}

getCompanies() {
    return this._http.get(URL_COMPANY)
        .map((response: Response) => response.json()).share()
        .catch(this.handleError);
}

getCompany(id: number): Promise<Company> {
    const url = `${URL_COMPANY}/${id}`;

    return this._http.get(url)
        .toPromise()
        .then(response => response.json() as Company)
        .catch(this.handleError);
}

company.component.ts

    ngOnInit(): void {


                this.route.params.switchMap((params: Params) => this.companyService.getCompany(+params['id']))
                .subscribe(company => this.company = company);
    }    

save(): void {
        this.companyService.update(this.company).subscribe(
           (worked) => { console.log("success")},
           (error) => { console.log("failed")}
        );
    }
like image 899
Flea Avatar asked Mar 26 '26 20:03

Flea


1 Answers

The first call is Preflighted requests which is for CORS.

Cross-domain requests are forbidden by default by Same-origin policy, therefore first request is to check allowance of cross-domain request.

If you click the first request, you would see 'Request Method: OPTIONS', and this Preflighted requests made by Angular HTTP module, you can do nothing with it.

like image 83
yenpu Avatar answered Mar 29 '26 12:03

yenpu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!