简体   繁体   中英

How to use angular js routing with laravel/lumen routing?

I am working on web application developed on laravel (latest version 5.*).I did a lot of search but not find exact solution for,how to use angular js routing with laravel routing.

Suppose urls like :

  • /viewItem/2
  • /editItem/5
  • etc,any urls having parameters

I want to fetch the data according to the parameters using angular js.The problem is that laravel having its own in-built routing (routes.php in /app/Http) and angular js routes using (ngRoute module).

  • What is the exact flow if both routing use in conjuction ?
  • How it can be implemented if want to avoid fetching data using creating object on each page where want a data from backend ? eg.$obj->getItem($id)
  • Where to place angular js routing ?

You need to make difference between the routes of your Laravel application and routes of your Angular application.

Define a route to display the angular application

// Http/routes.php

Route::get('/{js_route}', function() {
    return view('application');
})->where('js_route', '(.*)'); // Allow multiple URI segments

This route allows slashes to make your routing using ngRoute and it should be the last defined in your routes.php .

It will just render the a template that will be used to display your real Angular application.

// views/application.blade.php

<html>
    <body>
        <div class="container">
            <div ng-view></div> <!-- Here will come your partial views -->
        </div>
    </body>
</html>

Make the real application routing with Angular

Now, use ngRoute to define routes of your application and navigate between them.

// public/js/src/app.js

$routeProvider
    .when('/', {
        templateUrl: 'Default/index.html', // A simple HTML template
    });

// ...

Create API endpoints in Laravel

You will use XHR to retrieve your data from your Laravel application, in your Angular application.
To do this, just define new routes in the corresponding method (ie GET, POST), and create the corresponding controllers/actions.

// Http/Controller/FooController.php

class FooController extends \BaseController {

    /**
     * List all Foo entities in your app
     *
     * @return Response
     */
    public function index()
    {
        return Response::json(Foo::get());
    }
}

// Http/routes.php

Route::get('/api/foo', 'FooController@index')

Create Services/Factories to retrieve your data

// public/js/src/app.js

(function (app) {

    function FooService($http, $q) {
        this.getFoos = function() {
            return $http.get('/api/foo');
        };
    }

    app.service('Foo', FooService);

})(angular.module('yourApp'));

Like this, you can retrieve the data from laravel routes without browse the route directly. // public/js/src/app.js

function MainCtrl($scope, $http) {
    $scope.listFoo = function() {
        $http.getFoos()
            .then(function(response) {
                $scope.foos = response.data;
            }, function(error) {
                console.log(error);
            });
    };
}

app.controller('MainController', MainCtrl);

Use your application

Now, you are able to navigate in your application using the javascript routing only, and retrieve data from your backend by using the Laravel routing.

How I make it:
In my routes.php

/**
 * Redirects any other unregistered routes back to the main
 * angular template so angular can deal with them
 *
 * @Get( "{path?}", as="catch.all" )
 * @Where({"path": "^((?!api).)*$"})
 *
 * @return Response
 */
  Route::any('{path?}', function () {

    View::addExtension('html', 'php');

    return View::make('index');

  })->where("path", "^((?!api).)*$");


/*
|--------------------------------------------------------------------------
| API routes
|--------------------------------------------------------------------------
*/
  Route::group([
    'prefix' => 'api'
  ], function () {
     //here are my api calls
  });

I have created one index.html in my resources/view where is my base. You can put your js and css files in resources/assets or in public folder.

These technologies are different. Angular Routing is built to Single Page Application ( https://en.wikipedia.org/wiki/Single-page_application ). Laravel routing serving multiple pages.

But, if you want a Single Page Application, you should use a Laravel route / controller to give the application page.

You can also use ( https://laravel.com/docs/5.2/controllers#restful-resource-controllers ) Laravel resource controllers for sharing data between your JS app and the back-end.

But you mustn't mix Laravel and Angular routes.

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