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!
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")}
);
}
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.