I want to execute filter after Promises return values, am getting values from service but cannot execute further.
filter,map nothing applies on it. What am doing wrong here or we cannot apply filter from returned service function.? Any suggestion
Error: Property 'filter' does not exist on type 'void'.
This is my service.
loadUsers() {
fetch('http://api.icndb.com/jokes/')
.then((response) => {
return response.json();
}).then((data) => {
this.values = data
console.log(data);
}).catch((ex) => {
console.error('Error fetching users', ex);
});
}
then in my component.ts
export class SignUpComponent implements OnInit {
ngOnInit() {
this.newService.loadUsers().filter(res => res.id == '1');
}
constructor(private newService: MyDataService) { }
}
Promises. The function loadUsers()
contains a promise. You need to return the promise first:
loadUsers() {
return fetch('http://api.icndb.com/jokes/')
.then((response) => {
return response.json();
}).then((data) => {
this.values = data
console.log(data);
return data;
}).catch((ex) => {
console.error('Error fetching users', ex);
})
}
And then,
ngOnInit() {
this.newService.loadUsers().then(function(users) {
users.filter(res => res.id == '1');
})
}
loadUsers() returns a promise and not a value like a regular function. That means, loadUsers() takes time to complete. When it does, the promise object contains the now-resolved value. You can extract this value using <Promise object>.then()
which takes a function as an argument. The arguments of the function that you pass to .then (users in this case), contains what you're looking for.
First of all your function loadUsers do not return anything, you should write: return fetch('http://api.icndb.com/jokes/')...
, besides I'm not sure we promises have filter method. May be do this:
loadUsers() {
return fetch('http://api.icndb.com/jokes/')
.then((response) => {
return response.json();
}).then((data) => {
this.values = data
return data;
}).catch((ex) => {
console.error('Error fetching users', ex);
})
}
ngOnInit() {
this.newService.loadUsers()
.then(res => {
res.filter(res => res.id == '1');
})
}
continuation to other answers,your json response is object
and filter is Array method. json response contains value
property which is array of object. see the plnkr
export class App {
loadUsers() {
return fetch('https://api.icndb.com/jokes/')
.then((response) => {
return response.json();
}).then((data) => {
return data.value;
}).catch((ex) => {
console.error('Error fetching users', ex);
})
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.