【问题标题】:How to fix Cannot read properties of undefined (reading 'foreach') and response.json is not a function?如何修复无法读取未定义的属性(读取“foreach”)并且 response.json 不是函数?
【发布时间】:2021-12-28 19:35:54
【问题描述】:

我正在弄清楚我的代码有什么问题,但我看不到正确的答案。我收到此错误:

`TypeError: Cannot read properties of undefined (reading 'forEach') at renderUsers (forReviewCtrl.js:16)` 

还有这个错误

   `TypeError: response.json is not a function
    at getUsers (forReviewCtrl.js:7)
    at renderUsers (forReviewCtrl.js:14)
    at Object.<anonymous> (forReviewCtrl.js:36)`. 

我不明白。请有人可以向我解释为什么,因为我是 javascript 新手。

代码如下:

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();
})

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    您忘记了一些 asyncawait 关键字。既然你试图通过await 调用getUsers(),请将该函数设为async

    async function getUsers() {
      //...
    }
    

    然后在该函数中,await 异步操作:

    let response = await fetch(url);
    return await response.json(); 
    

    【讨论】:

    • 我仍然得到这个错误` TypeError: users.foreach is not a function at renderUsers (forReviewCtrl.js:16)` .. 我不知道为什么
    • @Gheh:users 可能不是数组。它是什么?就在尝试使用它之前,执行console.log(users),控制台会记录什么?
    【解决方案2】:

    您需要先解析fetch(url),然后才能调用.json()。目前,您正在尝试在 Promise 本身上调用 .json(),而不是它的结果。

    试试这个:

    function getUsers() {
        let url = '/tm-swagger-postman.json'; //API
    
        return fetch(url)
            .then(res => res.json())
            .catch(error => console.log(error));
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-12
      • 2022-11-22
      • 2019-12-08
      • 1970-01-01
      • 2019-08-19
      • 1970-01-01
      • 2021-02-27
      • 2021-02-28
      相关资源
      最近更新 更多