【问题标题】:how to filter json correctly with HttpClient angular 4如何使用 HttpClient angular 4 正确过滤 json
【发布时间】:2018-05-25 14:39:16
【问题描述】:

我在从 Http 迁移到 HttpClient 时遇到问题,这是我使用的代码

constructor(public navCtrl: NavController, public http: HttpClient, private alertCtrl: AlertController) {

 this.http.get('http://example.com/date.php')
.subscribe(data => {
  this.posts = data;
  this.postsfilter = data.filter(item => item.date == todayDate);

 });

 }

我已经包含了 import 'rxjs/add/operator/filter';但仍然出现错误:“对象”类型上不存在属性“过滤器”。如何正确过滤返回的json文件?

【问题讨论】:

    标签: angular typescript ionic-framework


    【解决方案1】:

    通过调用data.filter(),您将访问Array.prototype.filter() 方法,而不是RxJS 的过滤器方法。在您的情况下,data 包含一个没有方法 filter 的对象。这是导致错误的原因。

    要使用 RxJS 的过滤器,您需要使用 . 符号将其链接到您的 Observable

    看起来是这样的:

     this.http.get('http://example.com/date.php')
      .map(item => this.postsfilter = item)
      .filter(item => item.date === todayDate) // probably you would also want to go for strict equality
      .subscribe(data => {
        this.posts = data;
      });
    

    注意:从 RxJS 5.5 开始,您可以使用 pipe 方法。这基本上改变了链接 RxJS 操作符的方式。在此处了解更多信息:https://blog.hackages.io/rxjs-5-5-piping-all-the-things-9d469d1b3f44

    【讨论】:

    • 感谢您的回答,我需要 this.post 和 this.postsfilter。我如何使用 Array.prototype.filter()。因为如果我使用上面的方法,我将不得不调用 http.get 两次。我想在 ts 文件中过滤它
    • @jx1986 您可以使用 map 运算符将未过滤的值分配给 this.postfilter。我已经更新了我的答案。您使用.filter() 的方式已经正确。问题是返回的数据不是要循环的数组。
    • 感谢 Orlandster,您想详细说明如何绘制此图吗,我是这方面的新手。
    • 我已经更新了上面的代码。确保添加 import 'rxjs/add/operator/map' 以导入地图运算符。
    • 这对我更新应用程序有很大帮助。我已将其标记为答案,但由于我是该社区的新手,因此无法投票。干杯 n 有一个美好的一天奥兰斯特!
    【解决方案2】:

    “我已经包含了 import 'rxjs/add/operator/filter'; 但仍然出现错误:'Object' 类型上不存在属性 'filter'。如何正确过滤返回的 json 文件?” 因为你没有说data是数组

     this.http.get('http://example.com/date.php')
          .subscribe((data:any[]) => { //<--say that you received an array
             this.posts = data;
             //Here filter is filter of an ARRAY, not Rxjs
             this.postsfilter = data.filter(item => item.date == todayDate);
          });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-25
      • 2020-09-24
      • 2016-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-17
      相关资源
      最近更新 更多