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

這是我的模塊和配置。 我有簡單的應用程序。 我想添加一些功能,當用戶輸入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(...)不是構造函數

只需避免使用(...)=>{...}語法,因為AngularJS試圖使用new method()語法調用一個函數,但使用箭頭符號未能做到這一點。

.config($routeProvider=>{...}切換為.config(function($routeProvider){...} (以及其他類似情況)。

箭頭符號仍然可以使用,並且在 $http 調用中 很有用 ,例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM