2017-07-06 62 views
0

我有一個client對象,它通過內聯表單進行更新,如果我的服務無法成功更新客戶端,我希望它恢復到客戶端之前的狀態發生了變化。這是我到目前爲止:Angular:如果更新失敗,將對象還原爲原始

updateForm() { 
    let client_id = this.client.id 
    let curr_client = this.client 
    console.log("updating", curr_client) 

    this.clientService.update(this.client, "client", this.token).subscribe(
     data => { 
     // sets this client to new client returned from service 
     this.client = data 
     this.clientService.handleResponse("Successfully updated the client!") 
     this.clientService.setClient(this.client) 
     }, 
     err => { 
     console.log(curr_client) 
     this.clientService.handleResponse("Ut oh.. couldn't update the client!") 
     // attempt at reverting back but curr_client changes with this.client 
     this.client = curr_client 
     }, 
    () => this.editMode = false 
    ) 
    } 

我可以在故障塊中更改什麼來恢復客戶端?

+1

克隆對象並將其設置爲需要的變量。 –

回答

1

這是我做過什麼:

private currentProduct: IProduct; 
private originalProduct: IProduct; 

get product(): IProduct { 
    return this.currentProduct; 
} 
set product(value: IProduct) { 
    this.currentProduct = value; 
    // Clone the object to retain a copy 
    this.originalProduct = Object.assign({}, value); 
} 

我克隆對象儘快將產品從HTTP調用設置進行復印。然後,如果我需要恢復原狀,我可以使用原件。