AngularJS:使用$ window使用刷新转到上一个url

时间:2017-06-02 12:01:57

标签: angularjs

我是使用1.6.4版本的AngularJS的新手,我想要做的是重新定位用户在上一页上完成刷新。现在我回来了,但页面并不令人耳目一新。我知道如何使用单行代码来做到这一点。

用户login.component.js:

(function () {
    "use strict";

    var module = angular.module(__appName);

    function controller(authService, $window, $location, $document) {
        var model = this;

        model.$onInit = function () {
            //TODO:
        };

        model.login = function () {
            authService.login(model.email, model.password).then(function (response) {
                //$window.history.back();
                //$window.history.go(-1);
                //$window.location.href = '/';


                console.log("url:"+$document.referrer);
                //$document.referrer is showing undefined in console
                $location.replace($document.referrer);

            },
            function (response) {
                model.msg = response.error;
            });
        }
    }

    module.component("userLogin", {
        templateUrl: "components/user-login/user-login.template.html",
        bindings: {
            email: "<",
            password: "<"
        },
        controllerAs: "model",
        controller: ["authService", "$window", "$location", "$document" controller]
    });
}()); 

App.js:

"use strict";

//Global variables
var __apiRoot = "http://localhost:8000/api"; //No slash '/' at the end


var module = angular.module(__appName, [
    "ui.router",
    "angular-jwt"
]);

module.config(function ($stateProvider, $urlRouterProvider, $httpProvider, jwtOptionsProvider) {

    $urlRouterProvider.otherwise('/app/home');

    $stateProvider

        .state("app", {
            abstract: true,
            url: "/app",
            component: "appRouting"
        })

        .state("app.home", {
            url: "/home",
            component: "homeRouting"
        })

        .state("app.search", {
            url: "/search/:q",
            component: "searchRouting"
        });

    jwtOptionsProvider.config({
        tokenGetter: ['authService', function (authService) {
            return authService.getToken();
        }],
        whiteListedDomains: ['localhost']
    });

    $httpProvider.interceptors.push('jwtInterceptor');
});

3 个答案:

答案 0 :(得分:1)

如果您使用的是angular-ui-router且名称为先前状态,请使用:

$state.go('previousState', {}, { reload: true });

如果您没有以前状态的名称,那么您可以使用这段代码,它将在每次状态发生变化时运行。

$rootScope.previousState;
$rootScope.currentState;
$rootScope.$on('$stateChangeSuccess', function(ev, to, toParams, from,fromParams) {
  $rootScope.previousState = from.name;
  $rootScope.currentState = to.name;
  console.log('Previous state:'+$rootScope.previousState)
  console.log('Current state:'+$rootScope.currentState)
});

答案 1 :(得分:0)

您只需使用原生javascript即可刷新页面。 window.location.reload()

答案 2 :(得分:0)

使用$location.replace()。您可以使用$ document.referrer获取您来自哪里的URL。 $location.replace($document.referrer)

相关问题