How to handle page reload in AngularJS app for URL

2019-08-15 06:45发布

问题:

Am using Larvel 5 at server-side and AngularJs at client-side.

So I have these routes in AngularJS:

var adminApp = angular
  .module('adminApp', [
    'ngRoute',
    'ngResource'
  ])
  .config(['$httpProvider', '$routeProvider', '$locationProvider',
  function($httpProvider, $routeProvider, $locationProvider)
  {

      $httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';

      $routeProvider
      .when('/admin', {
          templateUrl: 'ng/templates/home/dashboard.html',
          controller: 'HomeController'
      })
      .when('/admin/users', {
          templateUrl: 'ng/templates/user/users.html',
          controller: 'UserController'
      })
      .otherwise({
          redirectTo: '/'
      });


      if(window.history && window.history.pushState){
          $locationProvider.html5Mode({
              enabled    : true,
              requireBase: false
          });
      };

  }]); 

An in Laravel I have this:

Route::group(['prefix' => 'admin'], function()
{
    Route::get('/',[
        'uses' => 'Admin\HomeController@getIndex',
        'as'   => 'admin.home.getIndex'
    ]);


    Route::get('/users',[
        'uses' => 'Admin\UserController@getIndex',
        'as'   => 'admin.users.getIndex'
    ]);

    Route::get('/users/approve/{id}',[
        'uses' => 'Admin\UserController@getApprove',
        'as'   => 'admin.users.getApprove'
    ]);

    Route::get('/users/delete/{id}',[
        'uses' => 'Admin\UserController@getDelete',
        'as'   => 'admin.users.getDelete'
    ]);

});

I have also created Controller for the route above.

When I access http://laravel.dev/admin in AngularJs everything works perfectly, also when I click on <a href="/admin/users"></a> everything works as expected,

However if i manually refresh the browser when am at http://laravel.dev/admin/users I hit the controller directly and no view is returned

Presently am using this workaround in my Controller methods and will like something better, because it redirects back to base URL instead of loading page specified in URL

public function getIndex()
{
    if(!Request::ajax()) return redirect()->route('admin.home.getIndex');

    $user = User::all();
    return response()->json($user);
}