3

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")}
        );
    }
Community
  • 1
  • 1
Flea
  • 11,176
  • 6
  • 72
  • 83
  • How many times your method save() and update() triggered? And do you have another places where you subscribing to update()? – Nikolai Dec 17 '16 at 08:55
  • I've put console.log statements in the click event and the click event itself is only fired once. I updated my code snippet to reflect that in my ngOnInit() I am doing subscribe, but this call returns a promise and not an observable. Otherwise I believe this is the only place I am subscribing. – Flea Dec 19 '16 at 15:40

1 Answers1

4

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.

yenpu
  • 96
  • 5