简体   繁体   English

AngularJS $ routeParams没有防御,但是有属性

[英]AngularJS $routeParams is undefiend, but property is there

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"
    });
})

this is my module and config. 这是我的模块和配置。 i have simple app. 我有简单的应用程序。 i want to add functionality that when the user enters the url for example.com/singleNews/2 - it opens the news with ID - 2 我想添加一些功能,当用户输入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);

So when i enter the url 所以当我输入网址

example.com/singleNews/2 example.com/singleNews/2

the routeParams is empty object, although when i click to that empty object in chrome console the property is there and it says "value below was evaluated just now " but when i add that console into TimeOut, it works and property is there. routeParams是一个空对象,尽管当我在chrome控制台中单击该空对象时,该属性存在,并且显示“下面的值刚刚被评估”,但是当我将该控制台添加到TimeOut中时,它起作用并且该属性存在。 I know that using setTimeOut() is not recommended in angularjs, so using $timeout solved the problem, but i want to understand what is the problem. 我知道在angularjs中不建议使用setTimeOut(),所以使用$ timeout解决了问题,但是我想了解问题所在。

You should be getting an error in your console: 您应该在控制台中遇到错误:

Function.prototype.bind.apply(...) is not a constructor Function.prototype.bind.apply(...)不是构造函数

Simply avoid using (...)=>{...} syntax as AngularJS tried to call a function with new method() syntax and fails to do that with an arrow notation. 只需避免使用(...)=>{...}语法,因为AngularJS试图使用new method()语法调用一个函数,但使用箭头符号未能做到这一点。

Switch .config($routeProvider=>{...} to .config(function($routeProvider){...} (and other similar cases). .config($routeProvider=>{...}切换为.config(function($routeProvider){...} (以及其他类似情况)。

Arrow notation can still be used and is useful with $http calls, eg: 箭头符号仍然可以使用,并且在 $http 调用中 很有用 ,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM