這是我的問題。如何在更新數據庫之前從服務中檢索數據(angular2)?
我有一個組件,用戶將能夠點擊收藏按鈕。該行爲將被存儲在數據庫中,並將更新「最喜歡」列的值。關鍵是,爲了更新這個值,我從數據庫中取出它,我這樣做: - 我在組件構造函數中執行get服務來檢索特定帖子的所有數據(名稱,描述,用戶,收藏夾......)。 - 我將喜歡列中的值賦給一個變量。 - 當我點擊收藏夾按鈕時,我將一個變量添加到變量(變量+ 1),然後將它發送到Web服務。
數據在數據庫中正確更新,但如果再次按下收藏夾按鈕,數據庫中將插入相同的值,因爲角度不會刷新我從服務中獲取的數據。它在我的組件更新數據的唯一方法是刷新頁面,但是這不是我想要的東西......
這裏是我的代碼:
service.ts
updateFav (id: any, variable: any): Observable<any> {
return this.http.put(`${this.baseUrl}updatePublicacion/${id}/`, variable, {headers: this.getHeaders()})
.map((res:Response) => res.json())
.catch((error:any) => Observable.throw(error.json().error || 'Server error'));
}
component.ts
@Component({
selector: 'publicacion-individual',
providers: [CynomysService],
templateUrl: './publicacion-individual.component.html',
styleUrls: ['publicacion-individual.component.css']
})
export class PublicacionindividualComponent implements OnInit {
idRecibido: any;
publicacionRecibida: Publicacion;
favoritos: any;
favToAdd: any;
response: any;
errorMessage: any;
constructor (private cynomysService: CynomysService, private route: ActivatedRoute, private _router: Router){
this.cynomysService.getPublicacionById(this.route.snapshot.params['id']).subscribe((p) => {this.publicacionRecibida = p});
}
ngOnInit() {
}
addFavorite() {
this.favoritos = this.publicacionRecibida[0].favoritos;
this.idRecibido = this.publicacionRecibida[0].idPublicaciones;
this.cynomysService.updateFav(this.idRecibido, (this.favoritos + 1)).subscribe(
result => this.response = result,
error => this.errorMessage = <any>error
);
}
}
我假設有,我需要做的事情,但我不」 t真的知道什麼,因爲我就像新的Angular ...
我試圖儘可能清楚,但問我,如果你不明白我的解釋。
更新數據庫後,只需調用GET請求來獲取所有的最愛嗎? – Alex