$locatioChangeStart触发多次

$locatioChangeStart fires multiple times

本文关键字:locatioChangeStart      更新时间:2023-09-26

基本上,我试图使一些数组应该有历史访问页面在我的应用程序。

$rootScope.$on('$locationChangeStart',
    function (event, next, current) {
    historyArray.push($location.path());
    console.log("history", historyArray);
});

一开始看起来还行,我的意思是["/page1", "/page2"],但随后它开始将"ChangeStart"效果相乘为["/page1", "/page2", "/page3", "/page3", "/page4", "/page4", "/page4"]等等。

有什么办法可以预防吗?

编辑。这只是一个例子,我需要$locationChangeStart为一些ngDialog模态和其他复杂的东西,但我面临类似的情况(如打开5模态在同一时间)

您可以添加一个条件来检查位置是否实际更改,并添加一个indexOf来确保页面不存在于数组中。

$rootScope.$on('$locationChangeStart',
    function (event, next, current) {
        if(next !== current && historyArray.indexOf(current) === -1) {
            historyArray.push($location.path());
        }
    }
);