【问题标题】:TypeError: Cannot read property 'path' of undefinedTypeError:无法读取未定义的属性“路径”
【发布时间】:2015-11-22 01:52:21
【问题描述】:

当登录成功时,我尝试重定向其他页面,在这种情况下,我使用了演示页面 index.html 成功。但是 $location.path 没有重定向到新页面。我收到错误类型错误:无法读取未定义的属性“路径”。

module LoginModule {
    export class LoginController {
        username: string;
        password: string;
        static $inject = ['$http','$location'];
        constructor(private $http : ng.IHttpService,private $location : ng.ILocationService){
        }
        login() {
            this.$http({
                method: 'POST',
                url: 'https://localhost:8061/nada/login',
                data : $.param({'username' : this.username, 'password' : this.password}),
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }}).success(function(data) {
                    this.$location.path("/success");
                   //alert("sucess");
                }).error(function(error) {
                    JSON.parse(error);
                    alert('No access available.');
                   // console.log(result);
                });
        }
    }

    angular.module('loginModule', ['ngRoute']).controller('LoginController', LoginModule.LoginController).config(['$routeProvider' ,function($routeProvider) {
        $routeProvider.
            when("/", {
            templateUrl: 'html/login.html'
        })

        .when("/success", {
            templateUrl: 'html/index.html',
            controller: 'clientsController'
        })
        .otherwise({redirectTo: '/'});

    }]);

}

我的代码中是否缺少某些内容。此外,我已将路由部分放在 .config 方法中,我可以将它移动到一个类中,因为我试图在 typescript 中这样做,如果是这样,我如何在 mycontroller 中访问它。

我有接受用户名和密码的登录页面。并打个休息电话

【问题讨论】:

    标签: angularjs typescript


    【解决方案1】:

    您需要在成功处理程序中保留词法范围,以便通过使用粗箭头函数将 this 用作类的上下文...

    }}).success(function(data) {
                    this.$location.path("/success");
    

    需要:

    }}).success((data) => {
                    this.$location.path("/success");
    

    胖箭头函数是你的朋友=>

    【讨论】:

    • 感谢您的回复,问题已解决,但现在它会将成功附加到我的网址。 localhost:8061/html/login.html#/success。我希望它重定向到 html/index.html
    • @AjinkyaKhavare 我很困惑...... this.$location.path("/succuss") 应该将 /success 附加到 url。这个答案解决了你的问题,你现在有一个新问题,你的代码没有做你想做的事。我认为您对 Angular 的工作原理有误解。
    • 我同意@KevinB 如果这解决了您关于未定义值的问题,请将其标记为已回答并努力解决您自己的$location.path 问题。如果您对此有任何疑问/疑问,请发布另一个问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 2018-02-26
    • 1970-01-01
    • 2015-05-25
    • 2021-12-31
    • 2021-11-24
    • 2019-10-20
    相关资源
    最近更新 更多