简体   繁体   中英

Redirection in angularjs

I am using angular js for a project, I have a login page, from where upon successful login the user is redirected to homepage. As of now i am using this code to redirect

request.success(function(data){
              $scope.response=data;
              NProgress.done();
              window.location.href = "/app/home.html";
             //$location.path('/homepage').replace();
        });

But the problem with this method is that the url in the browser shows /app/home.html#/feed which doesn't look good. I want this to achieve through routeprovider in angular but it is not working. My current app.js file looks like this

config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider.when('/feed', {templateUrl: 'partials/home/feed.html'});
$routeProvider.when('/profile', {templateUrl: 'partials/home/profile2.html'});
//  $routeProvider.when('/homepage', {templateUrl: '#/home.html'});
$routeProvider.otherwise({redirectTo: '/feed'});

I want the url in the broswer to look like app/homepage/feed using $location as i have tried in the comments. Any idea how i might be able to do it?

The function $locationProvider.html5Mode(boolean) is what you need.
Just do $locationProvider.html5Mode(true) and you shouldn't see any # s anymore.

It is on this page of the documentation

if you are not using Server Side Language/Routing,only you are using angularJs. then simply add this to completly remove # tag from angular.

angular.module('myApp', ['ngRoute'])
    .config(['$locationProvider', function($locationProvider) {
    $locationProvider.html5Mode(true);
}]);

But if you are using server side language then you will have to create a catch-all route so that any routes that are not specifically routed at server-side will be passed to angular routes.i am using here express server as a backend to catch route which are not mentioned in backend. i am assuming that you are using express.js:

app.get('*', function(req, res) {
res.render('index');
});

overall your server code will look like this:

var express = require('express'),
app = module.exports = express();
app.engine('.html', require('ejs').__express);
app.set('views', __dirname + "/views");
app.set('view engine', 'html');
app.use(express.static(__dirname + "/public"));
app.get('*', function(req, res) {
res.render('index');
});

for detail use this link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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