gpt4 book ai didi

angular - http.put 请求在 Angular2 中执行了两次

转载 作者:太空狗 更新时间:2023-10-29 18:20:51 25 4
gpt4 key购买 nike

我正在尝试更新从我的 Angular2 应用程序调用 API 的公司记录。我在调试时注意到 http 调用被执行了两次。我找到了另一个 stackoverflow thread这与此相同,答案是添加 .share() 由于冷热 Observables。我已将此添加到我的 http 调用中,但这并没有解决问题。感谢您的帮助!

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

最佳答案

第一个电话是Preflighted requests适用于 CORS。

Same-origin policy 默认禁止跨域请求,因此第一个请求是检查跨域请求的允许。

如果您单击第一个请求,您将看到“请求方法:选项”,而这个 Preflighted 请求由 Angular HTTP 模块发出,您无法对其进行任何操作。

关于angular - http.put 请求在 Angular2 中执行了两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41189293/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com