AngularJS $ routeParams是undefiend,但属性就在那里

时间:2018-01-09 14:27:45

标签: javascript angularjs routing angularjs-ng-route

UsState States

这是我的模块和配置。我有简单的应用程序。我想添加一些功能,当用户输入 example.com/singleNews/2 的网址时 - 它会打开ID为2的新闻

angular.module("newsApp",["ngRoute"])
.config($routeProvider=>{
    $routeProvider.when("/edit",{
        templateUrl : "views/addNewsView.html"
    });
    $routeProvider.when("/newsList",{
        templateUrl : "views/newsList.html"
    });
    $routeProvider.when("/singleNews/:newsId",{
        templateUrl : "views/singleNews.html"
    });
    $routeProvider.when("/",{
        templateUrl : "views/newsList.html"
    });
    $routeProvider.otherwise({
        redirectTo:"/newsList"
    });
})

所以当我输入网址

  

example.com/singleNews/2

routeParams 是空对象,但是当我点击Chrome控制台中的那个空对象时,该属性就在那里,它说“刚刚评估了下面的值” 但是当我将该控制台添加到TimeOut时,它的工作和属性就在那里。我知道在angularjs中不建议使用setTimeOut(),所以使用$ timeout解决了问题,但我想了解问题所在。

1 个答案:

答案 0 :(得分:2)

您应该在控制台中收到错误:

  

Function.prototype.bind.apply(...)不是构造函数

只需避免使用(...)=>{...}语法,因为AngularJS尝试使用new method()语法调用函数,并且无法使用箭头表示法执行此操作。

.config($routeProvider=>{...}切换为.config(function($routeProvider){...}(以及其他类似情况)。

仍然可以使用箭头表示法,并且对于 $http 调用很有用,例如:

$http.get(url).then( (res)=>{...} );