这是我的问题。如何在更新数据库之前从服务中检索数据(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