【问题标题】:how can I make a redirection with Angular.js?如何使用 Angular.js 进行重定向?
【发布时间】:2013-04-18 16:32:58
【问题描述】:

我想重定向到另一个路由,页面必须刷新并在服务器端处理,所以$location.path(url) 帮不了我。我试过window.location(url),但我有这个错误:window.location is not a function

我的 app.js:

    'use strict';
var app = angular.module('myApp', []).
  config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
    $routeProvider.when('/', {
        templateUrl: 'partials/index'});
    $routeProvider.when('/logout', {
        controller: 'logoutCtrl'});
    $routeProvider.otherwise({
        redirectTo: '/'});
    $locationProvider.html5Mode(true);
  }]);

我的注销Ctrl:

function logoutCtrl($scope, $location){
    $apply(function() { 
        $location.path("/users/logout"); 
    });
}

部分/索引包含此链接:

a(href='/logout') Logout

现在我将展示如何使用 Express.js 管理我的路由服务器端:

app.get('/', ctrl.index);
app.get('/partials/:name', ctrl.partials);
app.get('/users/logout', ctrl.logout);

exports.logout = function(req, res)
{
  console.log('logout');
  req.session.destroy(function(err){ // I destroy my session
   res.redirect('/'); // redirection to '/'
  });
}

现在,当我点击“注销”时,什么也没有发生,我只是在我的栏中看到这条路线localhost:3000/logout,但如果我输入localhost:3000/users/logout,我会得到预期的结果(会话被破坏并重定向到'/')

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    通过不工作代码的示例将很容易回答这个问题,但是有了这个 > 信息,我认为最好的信息是您在 > angularjs 摘要之外调用 $location.path。

    尝试在指令scope.$apply(function() {$location.path("/route");});"上执行此操作

    -Renan Tomal Fernandes

    【讨论】:

    • 它对我不起作用。我将把我的代码添加到我之前的帖子中:)
    • 它的$scope.$applyscope.$apply
    【解决方案2】:

    随你去吧:

    window.location.assign(url);
    

    或者:

    window.location.replace(url);
    

    不会将当前页面保存在浏览器会话历史记录中。

    【讨论】:

    • 这个问题是在 AngularJS 的上下文中提出的。绝不建议在 Angular 中使用非 Angular 服务,例如$window 是 Angular 服务。有很多原因在这里可能无关紧要。
    • 感谢您的讲座。用 $window 替换 window ,答案仍然有效。
    猜你喜欢
    • 2021-04-18
    • 1970-01-01
    • 1970-01-01
    • 2020-06-03
    • 2023-03-05
    • 2020-09-20
    • 1970-01-01
    • 2013-04-14
    • 1970-01-01
    相关资源
    最近更新 更多