【问题标题】:$location.path() not working..trying to redirect from .then in factory$location.path() 不工作..试图从 .then 在工厂重定向
【发布时间】:2014-07-14 20:57:56
【问题描述】:

无论我做什么,我都无法从工厂重定向到工作。我也在控制器中尝试过,但一直抛出错误。 TypeError: Cannot read property 'model.Email' of undefined

我知道帖子是成功的,我可以看到 200 并且它完美更新。这是我所拥有的:

显示我注入的工厂函数:

app.factory('accountFactory', function ($http, $q, $cookieStore, $location)

我的工厂:

factory.register = function (data) {
    return $http.post(urlBase + '/Register', data).then(function(response) {
        if (typeof response.data === "object") {
            $location.path('/login');
            return response.data;
        } else {
            return $q.reject(response.data);
        }
    }, function(response) {
        return $q.reject(response.data);
    });
};

控制器:

app.controller('accountCtrl', function ($scope, accountFactory) {
    $scope.hello = 'hello';

    $scope.registerUser = function () {
        var data = {
            "Email": $scope.email,
            "Password": $scope.password,
            "ConfirmPassword": $scope.confirmpass
        };

        accountFactory.register(data).then(function(data) {
            $scope.message = 'Successfully Created User!';

        }, function (error) {
            $scope.message = error.Message;

            // Invalid Email
            if (error['ModelState']['model.Email'])
                $scope.errorEmail = error['ModelState']['model.Email'][0];
            else
                $scope.errorEmail = null;

            // Invalid Pass / Confirm
            if (error['ModelState']['model.Password'])
                $scope.errorPassword = error['ModelState']['model.Password'][0];
            else if (error['ModelState']['model.ConfirmPassword'])
                $scope.errorPassword = error['ModelState']['model.ConfirmPassword'][0];
            else if (error['ModelState'][''])
                $scope.errorPassword = error['ModelState'][''][0];
            else
                $scope.errorPassword = null;
        });
    };
})

如果我删除该位置,当然一切都会完美无缺。添加位置时出现上述错误。我相信这与承诺有关,但我不确定。

【问题讨论】:

标签: angularjs angular-ui-router


【解决方案1】:

你需要兑现承诺。

factory.register = function (data) {
    return $http.post(urlBase + '/Register', data).then(function(response) {
        if (typeof response.data === "object") {
            $location.path('/login');
            return $q.resolve(response.data);
        } else {
            return $q.reject(response.data);
        }
    }, function(response) {
        return $q.reject(response.data);
    });
};

【讨论】:

  • 试过不行。我什至尝试过 $window.location.href = '/login' 但这不起作用。
  • 我很笨,上面的工作方式。我的 200 响应没有返回任何内容,所以 typeof 对象从来都不是真的。
猜你喜欢
  • 2013-08-11
  • 1970-01-01
  • 1970-01-01
  • 2013-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-23
相关资源
最近更新 更多