簡體   English   中英

$ http請求未從angular js中的服務返回響應

[英]$http request is not returning response from a service in angular js

在我的MEAN Stack應用程序中,當我想從服務返回靜態響應時,可以在控制器上獲得結果,而當我希望通過$ http請求獲得響應時,它不返回有效數據。


這是我的服務頁面 -

'use strict';
angular.module('products').factory('ProductSharedService', function($rootScope, $http) {
    var sharedService = {
        getProductList: function (theScope) {
            // Working 
            theScope.productList = {'testkey':'testvalue', 'demokey':'demovalue'};

            // Not working           
            $http.get('/products').then(function(response) {
                theScope.productList = response;
            });
        }
    };

    return sharedService;
});

這是控制器頁面 -

'use strict';

angular.module('core').controller('InviteController', ['$scope', 'ProductSharedService', '$stateParams', 'Authentication', '$http',
function($scope, ProductSharedService, $stateParams, Authentication, $http) {

$scope.getMembers = function() {
    $scope.productList = {};
    ProductSharedService.getProductList($scope);    //  Get all product from "ProductSharedService" service

    console.log(JSON.stringify($scope.productList));
    console.log($scope.productList);
};


這是靜態數據結果 您可以看到返回的對象。 在此處輸入圖片說明

結果與$ http request 現在什么都沒有了。 在此處輸入圖片說明

如果我將$ http請求放在控制器上,它將獲得以下內容-

{ "_id" : ObjectId("5537cdef3c3a11cd3baa90f8"), "artist" : "test artistname", "title" : "test title", "dimensions" : "140x145", "medium" : "test medium", "price" : 140, "provenance" : "test"}

我已經看過像其他問題這一個有關地雷,但這些並沒有幫助我當前的問題。

我在回答自己的問題只是為了幫助其他人知道我做了或建議要做的事情。

服務文件更改-

'use strict';

angular.module('products').service('ProductSharedService', function($http) {
    this.getProductList = function(){
        return $http.get('/products');
    };
});

控制器文件更改-

angular.module('core').controller('InviteController', ['$scope', 'ProductSharedService', '$stateParams', 'Authentication', '$http',
    function($scope, ProductSharedService, $stateParams, Authentication, $http) {
        $scope.getMembers = function() {
            var promise = ProductSharedService.getProductList();
            promise.then(function(data) {
                $scope.productList = data;
                console.log(JSON.stringify($scope.productList));
                console.log($scope.productList);
            });
        };
    }
]);

我發現以上更改對我的情況有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM