2017-06-14 58 views
1

我有以下问题。Resolving Promise Angular 2

在函数中我有一个承诺作为返回类型。该功能位于类层次结构中。

updateNodeValues(entity: String, data: {}): Promise<any>{ 
    let jsonBody = JSON.stringify(data); 
    let url = environment.endpointCore + '/api/' + entity + '/' + data['id']; 

    return this.http.put(url, jsonBody, this.options) 
     .toPromise() 
     .then(response => { 
     return response; 
     }) 
     .catch(this.handleError); 
    } 

此函数在类节点中。

onSubmit(): void{ 
    var currentForm = this.form.value; 
    var entityName = this.inflection.classify(this.node.type).toLowerCase(); 
    var requiredData = {}; 

    for(var i = 0; i < this.formItems.length; i++){ 
     this.formItems[i].value = currentForm[Object.keys(currentForm)[i]]; 
    } 

    for(var i=0; i<this.formItems.length; i++){ 
     requiredData[this.globalService.camelize(this.formItems[i].label)] = this.formItems[i].value 
    } 

    Promise.resolve(this.hierarchyService.updateNodeValues(entityName, requiredData)).then(response => { 
     alert(response.ok); 
     if(response.ok){ 
     this.globalService.showSuccessMessage('Values updated'); 
     this.refreshGui(requiredData); 
     } 
    }); 
    this.editMode = false; 
    } 

的问题是,当我试图解决的承诺,并调用this.refreshGui(requireddata)什么也没有发生。我已经阅读了关于脂肪箭头如何保留这个“上下文”,我不明白为什么调用这个方法没有做任何事情,而调用successMessage产生预期的结果。

我调用的方法如下所示,它也在类节点中。

private refreshGui(data: {}){ 
    this._node.data = data; 
    this.objectProperties = new Array(); 
    this.nodeChildren = new Array(); 
    for (var property in data) { 
     var propertyValue = data[property]; 
     if (propertyValue instanceof Array) { 
     this.nodeChildren.push({label: property, value: "total: ".concat(propertyValue.length.toString())}); 
     } else { 
     this.objectProperties.push({label: property, value: propertyValue}); 
     } 
    } 
    } 

回答

0

我发现工作的解决方案是实现自定义事件。问题是在异步回调分辨率内,this会“迷路”。胖箭头使我能够用这个方法调用类方法,但是其中的属性会“丢失”。由于这个原因,我从方法中取出逻辑,并将其放入回调部分,并在某些变量中设置预期和需要的结果。这个变量被传递给我的自定义事件,并在自定义事件处理程序中适当地设置为类变量。