加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular 2:如何使用Observable过滤器

发布时间:2020-12-17 09:03:44 所属栏目:安全 来源:网络整理
导读:我有一个调用API的服务,如下所示: return this._http .post(appSettings.apiUrl + 'SomeController/SomeAction',params,{withCredentials: true,headers: this.headers}) .timeoutWith(appSettings.maxTimeHttpCalls,Observable.defer(() = Observable.thro
我有一个调用API的服务,如下所示:
return this._http
        .post(appSettings.apiUrl + 'SomeController/SomeAction',params,{withCredentials: true,headers: this.headers})
        .timeoutWith(appSettings.maxTimeHttpCalls,Observable.defer(() => Observable.throw(this._feedbackService.timeout())))
        .map((response: Response) => response.json().data);

现在我想使用rxjs / add / operator / filter在该调用上实现一个过滤器函数,但我无法让它正常工作.

这是我采取的方法:

return this._http
        .post(appSettings.apiUrl + 'SomeController/SomeAction',Observable.defer(() => Observable.throw(this._feedbackService.timeout())))
        .filter(response => response.json().data.Type === 5)
        .map((response: Response) => response.json().data);

但无论我过滤什么,只要过滤器在那里,ngFor循环就不会产生任何效果.如果我删除它,一切都按预期工作.

我应该在地图之前或之后添加过滤器吗?

我可以像这样过滤响应JSON,还是需要使用其他语法?

示例JSON

以下是JSON响应的示例:

data: [
    {
        "Type": 5,"Description": "Testing","ID": "001525"
    }
]
filter()应该在map()之前还是之后取决于你想要做什么.

我想在你的情况下map()应该在filter()之前去,因为你想先从JSON解码数据然后过滤它.如果filter()中的条件解析为false,那么现在的方式将不会返回任何内容,因为您正在使用整个响应.也许这就是你想要的……

我不知道你的反应结构是什么,但我会选择这样的东西更有意义:

.map((response: Response) => response.json().data)
.filter(data => data.Type === 5)

编辑:

我将使用带有Observable.from()的concatMap()将数组转换为Observable流:

.map(content => response.json().data)
.concatMap(arr => Observable.from(arr))
.filter(item => item.Type === 5)
.subscribe(val => console.log(val))

观看现场演示:http://plnkr.co/edit/nu7jL7YsExFJMGpL3YuS?p=preview

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读