2016-03-31 56 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));