代码之家  ›  专栏  ›  技术社区  ›  Bahman Parsa Manesh

如何从angularjs中使用api获取数据的工厂获取控制器中的对象数据

  •  0
  • Bahman Parsa Manesh  · 技术社区  · 8 年前

    我有一个控制器,有两个功能,它们都称我为工厂的一个功能:

    .controller("Ctrl",function($scope,fetchDataFromServer){
    
      $scope.dataArray = [];
      $scope.dataArray2 = [];
    
      $scope.addNew = function () {
         fetchDataFromServer.fetchData()
         .then(function (data) {
            console.log(data);
            // $scope.dataArray.push(data);
         });
      };
    
      $scope.addNew2 = function() {
        console.log(fetchDataFromServer.fetchData());
      }
    
    })
    

    .factory('fetchDataFromServer', function ($http, $q) {
       return {
          fetchData: function() {
    
               return $http.get('//jsonplaceholder.typicode.com/posts/1')
                   .then(function(response) {
                       if (typeof response.data === 'object') {
                           return response.data;
                       } else {
                           // invalid response
                           return $q.reject(response.data);
                       }
    
                   }, function(response) {
                       // something went wrong
                       return $q.reject(response.data);
                   });
           }
       };
    })
    

    console.log 在add addNew中,给我一个对象:

    对象{userId:1,id:1,title:“sunt”,body:“quia”}

    {} “$$状态”:{} 状态:1 值:对象{userId:1,id:1,标题:“sunt aut facere repellat provident occaecati excepturi optio reprehenderit”,} :对象{} :对象{then:then() ,catch:catch(),finally:finally(),}

    我的密码 plunker

    1 回复  |  直到 8 年前
        1
  •  3
  •   Rahul Sharma    8 年前

    在第二个函数中,您正在打印承诺,而第一个函数您正在打印承诺的解析值/结果。

    $scope.addNew2 = function() {
        fetchDataFromServer.fetchData()
        .then(function (data) {
            console.log(data);
            // $scope.dataArray.push(data);
         });
    }