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 的网址时 - 它会打开 ID 为 2 的新闻
.controller("newsAppCtrl",['$scope','$location','$routeParams',($scope, $location, $routeParams)=>{
console.log($routeParams); //empty object
setTimeout(function () {
console.log($routeParams); //in this case property is there
},100);
所以当我输入网址
example.com/singleNews/2
routeParams 是空对象,尽管当我在 Chrome 控制台中单击该空对象时,该属性就在那里,并且显示“下面的值刚刚被评估” 但是当我将该控制台添加到 TimeOut 中时,它可以工作并且属性就在那里。我知道在 angularjs 中不建议使用 setTimeOut() ,因此使用 $timeout 解决了问题,但我想了解问题是什么。
最佳答案
您的控制台中应该会出现错误:
Function.prototype.bind.apply(...) is not a constructor
只需避免使用 (...)=>{...}
语法,因为 AngularJS 尝试使用 new method()
语法调用函数但失败带有箭头符号的。
将 .config($routeProvider=>{...}
切换为 .config(function($routeProvider){...}
(以及其他类似情况) .
箭头表示法仍然可以使用,并且对于 $http
调用很有用,例如:
$http.get(url).then( (res)=>{...} );
关于javascript - AngularJS $routeParams 未定义,但属性存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48170343/