2016-03-31 60 views
1

看来在2.0.0-beta.12版本中,他们从dart中删除angular2.http,转而使用在http类中构建的dart。通过http请求在dart中获得angular2的承诺?

但是,如果您要做类似下面的事情,那么在请求设置属性之前,属性为空。

class Component { 
    var property; 

    Component() { 
    HttpRequest.getString("/path/to/something") 
     .then((resp) { 
     property = JSON.decode(resp); 
     }); 
    } 
} 

我们真正想要的是承诺的财产承诺的持有人,直到承诺解决和视图更新。那么你怎么用角镖做飞镖?

还是有不同的飞镖/角2地道的方式来做到这一点?

回答

0

HttpRequest.getString(...)返回Future(在JS/TS土地Promise),否则您将无法调用.then(...)的结果。

您可以使用async/await

class Component { 
    var property; 

    Component() async { 
    await HttpRequest.getString("/path/to/something") 
     .then((resp) { 
     property = JSON.decode(resp); 
     }); 
    doSomethingAfterRequestReturned(); 
    } 
} 

没了 - 你不能在构造函数中使用async/await

替代品是静态方法或对象创建后的额外调用。无论如何,在构造函数中做广泛的工作是不好的习惯。

class Component { 
    Future<Component> createNewInstance() async { 
    var c = new Component(); 

    await HttpRequest.getString("/path/to/something") 
    .then((resp) { 
     c.property = JSON.decode(resp); 
    }); 
    return c; 
    } 

    var property; 
} 

和一个额外的呼叫

class Component { 
    getData() { 
    return HttpRequest.getString("/path/to/something") 
    .then((resp) { 
     property = JSON.decode(resp); 
    }); 
    } 

    var property; 
} 

使用它像

Component.createNewInstance().then((c) => print(c.property)); 

,并使用它像

var c = new Component() 
c.getData().then((_) => print(c.property));