【问题标题】:use of then / catch in $http call in angular在 $http 调用中使用 then / catch 角度
【发布时间】:2016-10-01 21:53:01
【问题描述】:

我的 Node 后端有以下端点:

usersRoute.get('/get', function(req, res) {

    //If no date was passed in - just use todays date

    var date    = req.query.date || dateFormat(new Date(), 'yyyy-mm-dd'),
        search  = req.query.search;

    users.getAllUsers(date, search)
        .then(function(results) {
           res.json(results); 
        }, function(err) {
            res.status(500).json({
                success: false, 
                message: 'Server error.',
                data: []
            });
        });
});

我已将我的 sql 表名更改为其他名称以触发 function(err){} 部分

当我在我的服务中使用它时,它看起来像这样:

function getUsers(date, search) {
            return $http.get('/api/users/get', {
                params: {
                    date: UtilsService.formatDate(date),
                    search: search
                }
            })
            .then(getData)
            .catch(handleErr);

            function getData(response) {
                return response.data;
            }

            function handleErr(err) {
                LoggerService.error('Could not retrieve users.', err ,'Ooops');
            }
        }

知道服务器将返回http status code 500,我认为它会直接返回catch block。但它也返回数据/这是then block中的undefined

我在控制器中这样使用我的服务:

function getUsers(date, search) {
            isAdmin();

            vm.loading = true;
            vm.filteredUsers = [];

            return UsersService.getUsers(date, search).then(function(data) {
                vm.loading = false;

                allUsers = data || [];
                vm.filteredUsers = allUsers.slice(0, 50);
                vm.distribution = UsersService.getDistribution(allUsers);

                return vm.filteredUsers;
            });
        }

我的问题是,因为then 部分是在我的service 中触发的。我正在尝试切片undefined

我的问题是:对于这种模式,有哪些最佳实践。

【问题讨论】:

  • 您确定您的服务器响应为 500?因为那肯定会触发捕获。
  • @FabioAntunes 我会稍微编辑一下我的问题。 catch 被触发,但也触发了“then 部分”。
  • 现在我明白了,我有适合你的解决方案

标签: javascript angularjs node.js http asynchronous


【解决方案1】:

你可以这样做

function getUsers(date, search, cb) {
      return $http.get('/api/users/get', {
           params: {
                date: UtilsService.formatDate(date),
                search: search
           }
      })
      .then(cb)
      .catch(handleErr);

      function handleErr(err) {
           LoggerService.error('Could not retrieve users.', err ,'Ooops');
      }
}

然后在你的控制器中

 UsersService.getUsers(date, search, function(data) {
        vm.loading = false;

        allUsers = data || [];
        vm.filteredUsers = allUsers.slice(0, 50);
        vm.distribution = UsersService.getDistribution(allUsers);
  });

【讨论】:

  • 现在似乎根本没有调用 catch。
【解决方案2】:

问题是您从 API 中捕获错误,然后返回由 .catch 创建的承诺。

快速示例

promise.then(function(data) {
  throw 'Some error';
}).catch(function (err) {
  console.log(err) // will output 'Some error'
}).then(function () {
  // This will run even though we have a catch before
});

那么我们怎样才能防止 .then 我们很容易在.catch 中抛出错误

promise.then(function(data) {
  throw 'Some error';
}).catch(function (err) {
  console.log(err) // will output 'Some error'
  throw 'You shall not pass'
}).then(function () {
  // This will not run
});

因此,在您的情况下,您有两种选择,一种是如我所说的抛出错误,另一种是将$q 服务注入您的服务:

function getUsers(date, search) {
    return $http.get('/api/users/get', {
        params: {
            date: UtilsService.formatDate(date),
            search: search
        }
    })
    .then(getData)
    .catch(handleErr);

    function getData(response) {
        return response.data;
    }

    function handleErr(err) {
        LoggerService.error('Could not retrieve users.', err ,'Ooops');
        return $q.reject(err);
    }
}

【讨论】:

  • 谢谢!只有一个问题;我用了你的第二个选项(使用 $q)。它仍然在'then'中并给我`Cannot read property 'data' of undefined`
  • @Nilzone- 我创建了一个 plunker,您可以在其中看到一切正常,plnkr.co/edit/v1DOevrEeepDrhDRoFe2?p=preview
  • 你说得对。我可能错过了什么。今天晚些时候我会仔细看看。谢谢你的例子! :)
  • 仍然有同样的问题。因为在'then'中响应对象是未定义的。我怀疑这与我的服务器发回数据的方式有关,因为常规的 http 请求似乎可以工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-19
  • 1970-01-01
  • 1970-01-01
  • 2021-12-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多