首页 > 解决方案 > 服务未按预期工作// 数据处理问题// 代码在控制器中编写时工作正常

问题描述

我有这个代码:

myNinjaApp.service('hexafy', function($http) {
this.myFunc = function (x) {
  return x.toString(16);
}

this.hexgetDoc= async function(){
    var rows;
    console.log("hittng api");
    // console.log(hexafy.myFunc(255));
    rows = await $http.get('http://173.212.250.58:7283/getCustomDoc').then(function(response){
        //handle your response here
        console.log("response");
        return response.data.cus.rows;
    });
    // console.log(rows);

    return rows;
}});

如果编写在控制器函数中,此代码运行良好。我只是在获取数据并将其放在表格中。我的控制器功能是:

$scope.getDoc= async function(){
        $scope.db =  await hexafy.hexgetDoc();
    }

在此方法之前,我将控制器中的服务代码用作:

$scope.getDoc= async function(){
         await $http.get('http://173.212.250.58:7283/getCustomDoc').then(function(response){
            //handle your response here
            console.log("response");
            $scope.db =  response.data.cus.rows;
        });
    }

这会在表中正确添加请求正文。

当我使用服务方法时。如果我两次调用该服务(通过单击两次按钮,则数据会被很好地添加。我知道为什么会发生这种现象。

这是正在发生的事情的 GIF

标签: angularjsxmlhttprequestangularjs-scope

解决方案


推荐阅读