簡體   English   中英

在多個控制器中使用AngularJs Service

[英]Using AngularJs Service in more than one controllers

我在這里掙扎着角。 我學到的是模塊的工廠和服務功能只創建一個對象的一個​​實例,它將屬性(函數和變量)與它相關聯。 並且該實例可在整個應用程序的控制器中使用。

在我的應用程序中,我創建了一個服務模塊userAngService ,如下所示:

var ser = angular.module('userAngService',[]);

ser.service('userAngService',['$cookies','$location','$http','$log','$rootScope',function($cookies,$location,$http,$log,$rootScope){
    this.user = {};
    $rootScope.username = {};
    $rootScope.user = {};

    /*this.loadUserData = function(username){
        return $http({
            method: 'GET',
            url: 'http://localhost:7070/storyBoard/webapi/profiles/'+username
        }).success(function(data){
            user = data.data;
            //return user;
        });
    };*/

    this.login = function(val){
        return $http({
            method: 'GET',
            url: 'http://localhost:7070/storyBoard/webapi/stories?username='+val.username+'&password='+val.password
        }).then(function(data){
            if(data.data==="Success"){
                $rootScope.username = val.username;
                $cookies.put("username", val.username);
                $http({
                    method: 'GET',
                    url: 'http://localhost:7070/storyBoard/webapi/profiles/'+val.username
                }).success(function(data){
                    console.log(data);
                    this.user = data;
                    console.log(this.user);
                });
                $location.path("/home");
            }else{
                window.alert('Wrong username or password');
            }
        });
    };

    this.logout = function(){
        $rootScope.user.username = "";
        $cookies.remove("username");
        $location.path("/Diary");
    };

    this.addToShelf = function(wsPublish){
        wsPublish.author = $rootScope.user.username;
        return $http({
            method: 'POST',
            url:'http://localhost:7070/storyBoard/webapi/stories',
            data: wsPublish
        }).then(function(data){
            this.user.stories.push(data.data);
        });
    };
}]);

它包含3個函數和私有變量this.user和2個rootScope變量$rootScope.username$rootScope.user 我們關心的函數是this.login()函數。

現在,

要使用此服務模塊,我創建了一個模塊AllControllers

 var app = angular.module('AllControllers',['userAngService']);

我用它關聯了2個控制器

第一控制器:

app.controller('LoginFormController',['$cookies','$rootScope','$log','$scope','userAngService','userBean',function($cookies,$rootScope,$log,$scope,userAngService,userBean){

    $scope.login = function(val){
        userAngService.login(val);
    };

    $scope.logout = function(){
        userAngService.logout();
    };

    $scope.publishGroup = function(obj){
        userBean.publishGroup(obj);
    };
}]);

*此控制器注入了userAngService依賴userAngService ,它的login()函數委托調用login() function of userAngService服務的login() function of userAngService

userAngServicelogin()函數更改其私有變量屬性。 然后我試圖在另一個控制器中使用,這就是所有問題所在。 當我在userAngService本身記錄返回的promise數據時,它已成功記錄但是當我嘗試訪問另一個控制器時,它只記錄一個空對象

第二個控制器(從那里訪問服務的私有變量):

 app.controller('ReachController',['$cookies','$scope','$rootScope','userAngService',function($cookies,$scope,$rootScope,userAngService){
    $scope.user = {};
    $scope.username = {};

    $scope.user = userAngService.user;
    console.log(userAngService.user);
    $scope.username = $cookies.get("username");

    /*userAngService.loadUserData($scope.username).then(function(data){
        $scope.user = data.data;
        console.log($scope.user);
    });*/

    console.log($scope.user);
    console.log($rootScope.user);

    $scope.logout = function(){
        userAngService.logout();
    };

    $scope.addToShelf = function(wsPublish){
        userAngService.addToShelf(wsPublish);
    };
}]);

那么一個空對象只能意味着對象屬性被定義為null並且不會被login()函數更新。 但是,在userAndService success回調;

console.log(data);
this.user = data;
console.log(this.user);

這些代碼行成功記錄返回的數據,而在ReachControllerSecond Controller的行中;

$scope.user = userAngService.user;
...
console.log($scope.user);

將此記錄到控制台:

Object {}

沒有錯誤,所以代碼是正確的,但在概念上我猜錯了。 請幫忙!

如果要返回數據使用工廠而不是服務。

服務始終返回包含數據的方法。

console.log(data);
this.user = data;
console.log(this.user); 

“this”對象用於Success函數的局部范圍。 它將覆蓋服務“this”對象。

我的猜測是問題在於服務和父模塊的命名 - userAngService 嘗試將模塊重命名為userAngServiceModule 當你向userAngService添加依賴時,無論你是指模塊還是服務,我都希望angular的DI會混淆。

this背景下諾言里面.then處理程序是不一樣的this服務的環境。

app.service("myService", function($http) {
    var myService = this;
    this.data = {};

    this.fetch = function(url) {
        //return promise 
        return (
            $http.get(url).then (function onFulfilled(response) {
                //Won't work
                //this.data = response.data;

                //Instead use the binding
                myService.data = response.data;
                //Return data for chaining
                return myService.data;
            }).catch (function onRejected(response) {
                console.log(response.status);
                //throw to chain rejection
                throw response;
            });
        );
    };
});

this背景下的onFulfilled的功能是不一樣的this服務的環境。 相反,結合this服務的情況下,以一個變量並使用該變量在onFulfilled承諾的功能.then方法。

另外要注意, this.data服務的變量被用在XHR之后的某個時間設定在未來 $http服務完成。 要確保數據可用,請使用fetch函數返回的promise。

在控制器中

var promise = myService.fetch(url);

promise.then (function onFulfilled(data) {
    $scope.data = data;
}).catch( function onRejected(errorResponse) {
    console.log(errorResponse.status);
});

暫無
暫無

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

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