2017-07-06 100 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调用设置进行复印。然后,如果我需要恢复原状,我可以使用原件。