【问题标题】:Angular 2 return filtered data from servicesAngular 2 从服务返回过滤数据
【发布时间】:2017-11-09 07:31:50
【问题描述】:

我是 Angular js 的新手,我想将过滤后的数据从服务返回到组件。

这是我的 json 样式

{
"emails": [
    {
        "list": [
        {
            "id": 1,
            "subject": "Test Subject 1"
        }, 
        {
            "id": 2,
            "subject": "Test Subject 2"   
        }]
    }, 
    {
        "list": [
        {
            "id": 3,
            "subject": "Test Subject 3"
        }, 
        {
            "id": 4,
            "subject": "Test Subject 4"
        }]
    }
]

}

这是我的服务

export class EmailService {

emails: any

constructor(private http: Http) {}


getEmailItem(id: number | string) {
    return this.http
    .get('../../../assets/js/data/email-list.json')
    .map(data => {data.json(); return data.json();});
}

}

我希望返回如下数据,我该怎么做?

{ “身份证”:1, “主题”:“测试主题 1” },

任何指南将不胜感激,谢谢

【问题讨论】:

    标签: angular2-services


    【解决方案1】:

    你可以把你的 json 弄平,然后应用过滤器,

    getEmailItem(id: number | string) {
        let flatData = [];
        return this.http
        .get('../../../assets/js/data/email-list.json')
        .map(data => {data.json(); return data.json();})
        .map(this.flatEmailList)
        .filter(email => email.id == id);
    }
    
    flatEmailList(data){
      let flatData = [];
      data.emails.map(emails => flatData = flatData.concat(emails.list));
      return  flatData;
    }
    

    【讨论】:

    • 您好,感谢您的回答,它返回了我想要的数据,但我收到一条错误消息:“any[]”类型上不存在属性“id”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-13
    • 2017-10-12
    • 2016-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多