2
我正在嘗試更新從我的Angular2應用程序調用API的公司記錄。我在調試時注意到http調用正在執行兩次。我發現另一個stackoverflow thread,這是相同的,答案是加入.share()
由於熱和冷觀測。我已將此添加到我的http呼叫中,但這並未解決問題。我感謝任何幫助!http.put請求在Angular2中執行兩次
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")}
);
}
你的方法save()和update()觸發了多少次?你有另一個地方你訂閱更新()? – Nikolai
我已經在click事件中放置了console.log語句,並且click事件本身僅被觸發一次。我更新了我的代碼片斷,以反映我在ngOnInit()中所做的訂閱,但此調用返回一個承諾而不是可觀察的。否則,我相信這是我訂閱的唯一地方。 – Flea