2017-05-22 51 views
0

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

我试图尽可能清楚,但问我,如果你不明白我的解释。

+1

更新数据库后,只需调用GET请求来获取所有的最爱吗? – Alex

回答

0

看起来像你的this.publicacionRecibida更新后没有更新。

如果你有控制服务器端,那么也许它是很好的让它返回你的update服务。如果没有,你将不得不再次调用this.cynomysService.getPublicacionById,您更新后:

this.cynomysService.updateFav(this.idRecibido, (this.favoritos + 1)) 
    .flatMap(
    result => { 
     this.response = result; 
     //call the get again to refresh your data; 
     return this.cynomysService.getPublicacionById(this.route.snapshot.params['id']); 
    }) 
    //final processing 
    .subscribe(
    result => {}, 
    error => this.errorMessage = <any>error, 
    ()=>{}); 
+0

谢谢你的快速回答。我使用了组件内的代码,但它给了我这个错误:类型'(result:any)=> void'的参数不能分配给类型为'(value:any,index:number)的参数=> ObservableInput <{}>' 。 类型'void'不可分配为键入'ObservableInput <{}>'。已更新 – Beep

+0

。没有正确读取您的代码。你可以使用'flatMap'来链接观察对象。 – CozyAzure

+0

再次感谢您的时间。现在它给了我这个错误:类型'(final:any)=> void'的参数不能分配给类型为'()=> void'的参数。我试图摆脱“final => {}部分,但是当方法执行时抛出=> this.cynomysService.updateFav(...)。flatMap不是函数 at PublicacionindividualComponent.webpackJsonp.98.PublicacionindividualComponent。 addFavorite我不确定它是否会抛出错误,只是没有final => {}部分 – Beep