I am figuring out what's the problem with my code but I can't look the right answer. I am getting this error:
`TypeError: Cannot read properties of undefined (reading 'forEach') at renderUsers (forReviewCtrl.js:16)`
and this error
`TypeError: response.json is not a function
at getUsers (forReviewCtrl.js:7)
at renderUsers (forReviewCtrl.js:14)
at Object.<anonymous> (forReviewCtrl.js:36)`.
I don't understand. Please someone can explain to me why because I am new to javascript.
Here is the code:
angular.module('newApp').controller('forReviewCtrl', function(){
function getUsers() {
let url = '/tm-swagger-postman.json'; //API
try {
let response = fetch(url);
return response.json(); //error
} catch (error) {
console.log(error);
}
}
async function renderUsers() {
let users = await getUsers();
let html = '';
users.foreach(user => { //the error
let htmlSegment = `<table border="3px;">
<tr>
<td>"${user.fname}"</td>
<td>"${user.last}"</td>
</tr>
<tr ng-repeat="user in users">
<td>"${user.fname}"</td>
<td>"${user.last}"</td>
</tr>
</table>
</div>`;
html = htmlSegment;
});
let container = document.querySelector('.container');
container.innerHTML = html;
}
renderUsers();
})
CodePudding user response:
You're forgetting some async
and await
keywords. Since you're trying to await
the call to getUsers()
, make that function async
:
async function getUsers() {
//...
}
Then within that function, await
the asynchronous operations:
let response = await fetch(url);
return await response.json();
CodePudding user response:
You need to resolve the fetch(url)
before being able to call .json()
on it. Currently, you're trying to call .json()
on the promise itself, not the result of it.
Try this:
function getUsers() {
let url = '/tm-swagger-postman.json'; //API
return fetch(url)
.then(res => res.json())
.catch(error => console.log(error));
}