AngularJS服务:无法访问子属性

时间:2017-07-31 08:23:09

标签: angularjs

我已经创建了一项服务,以便在用户登录后获取用户的详细信息,因此我可以将其提供给所有角度控制器:

var app = angular.module('myApp', ['ui.calendar', 'ui.bootstrap']);

app.service('authUser', ['$http', function ($http) {
var _currentUser = {};
$http.get("/Home/GetUser", {
    cache: false
}).success(function (data) {
    _currentUser.userid = data.userId;
    _currentUser.role = data.userRole;
    _currentUser.departmentid = data.departmentId;
    _currentUser.department = data.userDepartment;
});
this.currentUser = _currentUser;
}]);

app.controller('eventController', ['$scope', 'authUser', '$http', 'uiCalendarConfig', '$uibModal', function ($scope, authUser, $http, uiCalendarConfig, $uibModal) {
$scope.currentUser = authUser.currentUser;

当我尝试显示输出时,它看起来没问题:

<div>
    <label>{{currentUser}}</label>
    <label>Id: {{currentUser.userid}}, Role: {{currentUser.role}}, Department Id: {{currentUser.departmentid}}, Department Name: {{currentUser.department}}</label>
</div>

输出:

{"userid":"29aa607a-d36b-46bb-a3a7-16bead5f4706","role":"Super 
Admin","departmentid":1,"department":"MIS"} Id: 29aa607a-d36b-46bb-a3a7-16bead5f4706, Role: Super Admin, Department Id: 1, Department Name: MIS

但是当我尝试在我的代码中使用currentUser的属性时,没有传递任何东西。例如:

$http.get("/Home/GetVenues", {
    cache: false,
    params: {
        currentdepartment: $scope.currentUser.departmentid
    }
}).success(function (data) {
    // ...
})

我试过

$scope.currentdept = $scope.currentUser.departmentid;

或者

$scope.currentdept = authUser.currentUser.departmentid;

但这两个都没有返回; m;

如果我在这里遗漏了一些非常简单的东西,我很抱歉,但我是土豆,请怜悯; m;

如果它完全相关,那么我的HomeController是我的GetUser方法:

public JsonResult GetUser()
    {
        if (Request.IsAuthenticated)
        {
            ApplicationDbContext db = new ApplicationDbContext();
            var user = db.Users.Find(User.Identity.GetUserId());
            var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(ApplicationDbContext.Create()));
            string id = userManager.FindById(User.Identity.GetUserId()).Id;
            IList<string> roleNames = userManager.GetRoles(id);
            ReservationsDatabaseModel dept = new ReservationsDatabaseModel();
            Department department = dept.Departments.Find(user.DepartmentID);

            userDepartmentRole user_department_role = new userDepartmentRole();
            user_department_role.userId = user.Id;
            user_department_role.departmentId = user.DepartmentID;
            user_department_role.userDepartment = department.Name;
            user_department_role.userRole = roleNames.FirstOrDefault();

            return new JsonResult { Data = user_department_role, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }
        else
        {

            userDepartmentRole user_department_role = new userDepartmentRole();
            user_department_role.userId = "0";
            user_department_role.departmentId = 0;
            user_department_role.userDepartment = "0";
            user_department_role.userRole = "Guest";
            return new JsonResult { Data = user_department_role, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }
    }

2 个答案:

答案 0 :(得分:0)

您的通话仅在返回GetUser API后才有效,您可以通过点击按钮调用GetVenues来测试,而不是在init上运行。

答案 1 :(得分:0)

/Home/GetVenues的提取需要等待authUser数据从服务器到达。

更改服务以保存承诺:

app.service('authUser', ['$http', function ($http) {
    var _ = this;
    this.currentUser = {};

    this.currentUserPromise = $http.get("/Home/GetUser", {
        cache: false
    }).then(function (response) {
        var data = response.data;
        _.currentUser.userid = data.userId;
        _.currentUser.role = data.userRole;
        _.currentUser.departmentid = data.departmentId;
        _.currentUser.department = data.userDepartment;
        return data;
    });
}]);

然后在控制器中使用该承诺:

authUser.currentUserPromise.then(function(userData) {

    $http.get("/Home/GetVenues", {
        cache: false,
        params: {
            currentdepartment: userData.departmentid
        }
    }).then(function (response) {
        var data = response.data;
        // ...
    })

});

这样,控制器在从authData获取之前等待/Home/GetVenues从服务器到达。