[英]Filter response data from httpClient based on a certain condition in angular 8
Hi I am new to Angular(V8). 嗨,我是Angular(V8)的新手。 I am making a post request and would like to filter the response data based on a condition. 我正在发出发布请求,并希望根据条件过滤响应数据。 When I tried, I got the following error, filter is not a function. 当我尝试时,出现以下错误,filter不是函数。 Could you please guide so that it would be helpful for me. 请您指导一下,以便对我有所帮助。
Sample Response = {
className:"a",
dept_name:"b",
jsonData:[
{
"type":"branch",
"value":"1"
},
{
"type":"branch",
"value":"1"
},
{
"type":"dev",
"value":"2"
},
{
"type":"dev",
"value":"2"
},
{
"type":"dev",
"value":"2"
},
{
"type":"branch",
"value":"1"
}
]
}
I want to filter the jsonData where type="dev". 我想过滤jsonData,其中type =“ dev”。
this.http.post('someurl')
.map(item => this.filterVal = item)
.filter(item => item.type=== "dev")
.subscribe(data => {
this.posts = data;
})
Expected Output :
jsonData:[
{
"type":"dev",
"value":"2"
},
{
"type":"dev",
"value":"2"
},
{
"type":"dev",
"value":"2"
}
]
Response.jsonData.filter(x => {x.type === "dev"})
You are using version 8, so if started with CLI, rxjs 6 is automatically included. 您使用的是版本8,因此如果从CLI启动,则会自动包含rxjs 6。 You should move on to that, meaning pipeable operators. 您应该继续讲下去,这意味着可管道运算符。 Also we usually allocate http-requests to be made in a service and the components just subscribe to the result, that is what I have done in the StackBlitz below. 同样,我们通常会分配要在服务中进行的http请求,而组件只订阅结果,这就是我在下面的StackBlitz中所做的。 Here I will use your code though, but refer to the StackBlitz please. 在这里,我将使用您的代码,但是请参考StackBlitz。
Change your code to: 将您的代码更改为:
import { map } from 'rxjs/operators';
// ...
this.http.post('someurl')
.pipe(
map(val => this.filterVal = val),
// use filter to get the values you want
map(items => items.jsonData.filter(item => item.type === 'dev'))
)
If you insist to do it with older rxjs, it looks very similar: 如果您坚持使用较旧的rxjs进行操作,则它看起来非常相似:
this.http.post('someurl')
.map(val => this.filterVal = val)
.map(items => items.jsonData.filter(item => item.type === 'dev'))
But please embrace the newer version. 但是,请接受较新的版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.