【发布时间】:2017-05-22 16:22:18
【问题描述】:
这是我的问题。
我有一个组件,用户可以在其中单击收藏按钮。该操作将存储在数据库中,并将更新“收藏”列的值。关键是,为了更新该值,我从数据库中获取它,我这样做: - 我在组件构造函数中执行 get 服务来检索特定帖子的所有数据(名称、描述、用户、收藏夹......)。 - 我将最喜欢的列中的值赋予一个变量。 - 当我单击最喜欢的按钮时,我向该变量(变量 + 1)添加一个,并将其发送到 Web 服务。
数据库中的数据已正确更新,但如果我再次按下收藏按钮,相同的值将插入数据库中,因为 angular 不会刷新我从服务中获得的数据。它更新组件中数据的唯一方法是刷新页面,但这不是我想要的......
这是我的代码:
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
);
}
}
我想我需要做一些事情,但我真的不知道是什么,因为我在 Angular 中很陌生...
我尽量说清楚,但问我你是否不明白我的解释。
【问题讨论】:
-
更新db后,调用get请求获取所有收藏夹?