Angular 2 Typescript Observable返回第一个对象结果

时间:2017-01-28 22:22:43

标签: angular typescript observable

我有Observable的以下邮政服务

select created, name, new_users, possible, 
       (new_users::FLOAT / possible) as penetration,
       (sum(new_users::FLOAT) over (partition by name order by created) /
        sum(possible::FLOAT) over (partition by name order by created)
       ) as cum_amt

from mom_users
where new_users > 10
order byname, created desc;

服务器使用刚刚创建的对象进行响应。现在我想检索那个对象并将其保存到组件中的变量。

// Add a new order
addOrder(body: Object): Observable<Order[]> {
    let bodyString = JSON.stringify(body);
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    return this.authHttp.post(this.ordersUrl, bodyString, options)
        .map(response => response.json())
        .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
}

由于结果是observable []类型,我无法分配给对象var。如何将observable的内容放入对象var myOrder?

2 个答案:

答案 0 :(得分:1)

如果您确定该服务返回单个对象,只需更新您的类型,如

addOrder(body: Object): Observable<Order> {

它应该可以正常工作。

在订阅部分,

// Subscribe to observable
orderOperation.subscribe(
    order => {
        // Emit list event
        ...
        this.myOrder = order
    });

答案 1 :(得分:0)

尝试这个解决方案。

  orderOperation.subscribe(
orders => {
    if(orders!=undefined){

         this.myorder=orders;
     }
});