2017-05-22 47 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