【问题标题】:Projecting into subobject when retrieving observable (typescript/angular)检索可观察对象时投影到子对象(打字稿/角度)
【发布时间】:2017-08-16 16:40:00
【问题描述】:

我有一些从 API 到 Angular 服务的示例 json,像这样的对象集合:

{
  "data": {
    "id": 1,
    "title": "one"
  },
  "stats" : {
    "voteCount": 8
  }
}

“数据”部分是我想以反应形式以角度提交回来的内容,所以我真的希望我的 observable 是一个只有 id 和标题的对象集合:

export class SimpleIssue {
  id: number;
  title: string; 
}

在我的角度服务中,我得到如下数据:

getItems(): Observable<SimpleIssue[]> {
    return this.http.get(this.apiUrl + 'simpleissues/')
        .map((response: Response) => <SimpleIssue[]> response.json())
        .do(thedata => console.log('all: ' + JSON.stringify(thedata)))
        .catch(this.handleError);
}

我会想如果我将 response.json() 更改为 response.json().data 可能会起作用,或者如果我在该行之后添加另一个 .map 类似:

.map(blah => blah.data)

但没有运气。顺便说一句,如果我将它作为“任何”类型引入,我可以输入 {{ myItem.data | json }} 并得到我所期望的,因为它正在处理每个集合对象。

我可以让这个工作,还是我错过了为每个视图发送不同视图模型等的基本概念?

谢谢

【问题讨论】:

    标签: json angular typescript


    【解决方案1】:

    尚未测试,但这应该适用于您的情况:

    getItems(): Observable<SimpleIssue[]> {
        return this.http.get(this.apiUrl + 'simpleissues/')
            .map((response: Response) => <any[]> response.json())
            .map((arr: any[]) => arr.map(i => i.data))
            .do(thedata => console.log('all: ' + JSON.stringify(thedata)))
            .catch(this.handleError);
    }
    

    【讨论】:

    • 像一个魅力一样工作,不会想到我自己一个人。干杯!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-13
    • 1970-01-01
    相关资源
    最近更新 更多