H
H
HoHsi2016-02-04 15:09:10
Angular
HoHsi, 2016-02-04 15:09:10

How to properly use routing in Express + Angular?

Good afternoon!
How to correctly implement routing in Angular using template parts.
Now I had to reinvent the wheel, and do something like this routing:
Express :

app.get('/', (req, res) => {
  if (req.xhr){
    res.render('partial-index');
  } else {
    res.render('index');
  }
});

Angular :
.config(['$routeProvider', '$locationProvider',
  ($routeProvider, $locationProvider) => {
    $locationProvider.html5Mode({
      enabled: true,
      requireBase: false
    });

    $routeProvider
    .when("/", {
      templateUrl: '/',
      controller: 'MainCtrl'
    })
    .when("/about", {
      templateUrl: '/about',
      controller: 'AboutCtrl'
    });
});

Those. in fact, for each url, I check the XHR to see if it is a request, and then either give out a full page or a partial. I understand that something is wrong here, but I did not understand how to make a more adequate implementation.
If you use '*' then the page with the script will sometimes load in infinite mode and the browser will crash from a leak.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly Pasyuta, 2016-02-04
@pasutavitaliy

Most likely, if you use routing from angular, then your express should work as an api and it should not draw anything.
Something like this on the client

.state('login', {
  cache: false,
  url: '/login',
  templateUrl: 'templates/auth/login.html'
});
---------
.controller('loginCtrl', function ($scope, Request, $state) {

        $scope.login = function (operator) {
            Request.sendRequest('Your/path/to/express/api/current/method', obj).then(
                function resolve(resp) {
                   // handle success answer, call function to render some partial of html etc.

                },
                function reject(resp) {
                  //  handle error
                }
            );
})

and your express, which works on the api principle, will return only data, all rendering will be done by angular,
all work with templates, etc.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question