Giter Site home page Giter Site logo

karlhepler / angular-middleware Goto Github PK

View Code? Open in Web Editor NEW
33.0 3.0 4.0 54 KB

Laravel-like middleware for Angular ui.router and ngRoute

License: MIT License

JavaScript 90.79% HTML 9.21%
middleware ngroute router laravel angular angularjs ui-router

angular-middleware's Introduction

Angular Middleware

Laravel-like middleware for ngRoute & ui.router

Deprecation Notice

Please, by all means, if you use Angular 1x you can continue to use this... but don't expect this to be updated going forward. If you want to make feature additions or bug fixes, then I suggest forking it. I've moved away from Angular 1x and I'm focusing on Angular 4+ and VueJS. This plugin served me well several times in real-world production environments, and I hope it can do the same for you.

Installation

  1. Get it on your computer

    • Bower bower install --save angular-middleware
    • NPM npm install --save angular-middleware
    • GitHub git clone https://github.com/oldtimeguitarguy/angular-middleware
  2. Include angular-middleware.min.js in your app, whichever way you choose

  3. Include the module that works for you:

    • ui.router.middleware
    • ngRoute.middleware

Configuration & Examples

ngRoute Example on Plnkr

ui.router Example on Plnkr

// An app with ui.router...
var app = angular.module('app', [
	'ui.router',
	'ui.router.middleware'
]);

// An app with ngRoute...
var app = angular.module('app', [
	'ngRoute',
	'ngRoute.middleware'
]);

/////////////////////////////////////////////////////////
// Either way you go, the rest is essentially the same //
/////////////////////////////////////////////////////////

/**
 * First, you need to map your middleware functions.
 * This can be done cleanly with separate files
 * for each middleware function. You can do that
 * a number of different ways. I'll just show you
 * the basics.
 */
app.config(['$middlewareProvider',
function($middlewareProvider)] {

	// If you want middleware,
	// then you need to map some middleware
	// functions to names that you can
	// reference in your routes
	$middlewareProvider.map({

		/** Don't allow anyone through */
		'nobody': function nobodyMiddleware() {
			//
		},

		/** Let everyone through */
		'everyone': function everyoneMiddleware() {
			// In order to resolve the middleware,
			// you MUST call this.next()
			this.next();
		},

		/** Redirect everyone */
		'redirect-all': function redirectAllMiddleware() {
			// If you are using ui.router,
			// then you must choose a state name
			this.redirectTo('another-state-name');

			// If you are using ngRoute,
			// then you must actually put in
			// the new url that you would use in
			// $location.path()
			this.redirectTo('/another-path');

			// An object of parameters can also
			// be provided which will be used to
			// populate the url query parameters
			// ex. /another-path?redirectFrom=current-path
			this.redirectTo('/another-path', {
				redirectFrom: 'current-path'
			});

			// If you are using ui.router,
			// you can also change transitionTo options
			this.redirectTo('another-state-name', null, { reload: false });
		},

		/** Continue, but log the parameters */
		'log': ['$log', function logMiddleware($log) {
			// Notice that we used dependency injection to get $log.
			// You have access to the route parameters with this.params
			$log.debug(this.params);

			// Keep on truckin'
			this.next();
		}],

		/** It will wait for async requests too! */
		'async-auth': ['$http', function asyncAuth($http) {
			// We'll need access to "this" in a deeper context
			var request = this;

			// Grab something from the server
			$http.get('/verify')

			// The server has responded!
			.then(function success(res) {
				if ( res.isVerified ) {
					return request.next();
				}

				request.redirectTo('another-state-or-path');
			},

			function fail(err) {
				request.redirectTo('another-state-or-path');
			});
		}]

	});

});

/**
 * Now you're ready to use your middleware!
 * All you have to do is put them in your routes.
 * Each middleware is processed in the order you list them.
 *
 * The principle is the same for ui.router and ngRoute.
 * I'll show you both to make sure the dead horse is sufficiently beaten.
 */

 /** ui.router */
 app.config(['$stateProvider', function($stateProvider) {
 	$stateProvider

 	// You can have just one middleware,
 	// represented by a string
 	.state('my-state-name', {
 		...
 		middleware: 'a-single-middleware'
 	})

 	// You can have multiple middleware
 	// separated by pipes. aka. |
 	.state('another-state-name', {
 		...
 		middleware: 'one-middleware|another-middleware'
 	})

 	// You can have multiple middleware as an array
 	.state('a-third-state-name', {
 		...
 		middleware: ['one-middleware', 'another-middleware', 'another-nother-middleware']
 	})
 }]);

 /** ngRoute */
 app.config(['$routeProvider', function($routeProvider) {
 	$routeProvider

 	// You can have just one middleware,
 	// represented by a string
 	.when('/my-path', {
 		...
 		middleware: 'a-single-middleware'
 	})

 	// You can have multiple middleware
 	// separated by pipes. aka. |
 	.when('/my-other-path', {
 		...
 		middleware: 'one-middleware|another-middleware'
 	})

 	// You can have multiple middleware as an array
 	.when('/my-third-path', {
 		...
 		middleware: ['one-middleware', 'another-middleware', 'another-nother-middleware']
 	})
 }]);

$middlewareProvider

  • $middlewareProvider.map(<object>) This is how you define and name your middleware.

  • $middlewareProvider.bypassAll(<boolean>) This gives you a way to easily bypass all middleware... as if it didn't exist!

  • $middlewareProvider.global(<string|array>) If you want to apply some middleware to all routes, you can easily do it here. The same rules apply to setting up middleware on routes, ie. you can use a string, a string with pipes, or an array of middleware names. NOTE: Anything defined here will be called before the route middleware is called.

Things you can do inside your middleware functions

If you don't know what I'm talking about, look at the example above

  • this.next() must be called to resolve the middleware and either go to the next middleware or resolve the route

  • this.redirectTo(dest [,params [,options]]) can be called to immediately redirect

    • dest (required): A path (ngRoute) or state name (ui.router) to redirect to
    • params (optional): A params object to be used to populate query parameters (ngRoute) or $stateParams (ui.router)
    • options (optional): An object of transitionTo options (only used with ui.router)
  • this.route is the destination route path

  • this.params is an object that contains the current route parameters

angular-middleware's People

Contributors

hjylewis avatar joshkoberstein avatar karlhepler avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

angular-middleware's Issues

Including module breaks <ui-view> rendering

When I include the module, all of my states stop rendering their templates. There are no errors in the console either.

angular.module('app.core', ['ngCookies', 'ui.router', 'ui.router.middleware']);

How to (1) access the destination route (2) handle abstract routes

Love this new middleware. After coding a new NodeJS backend it got me thinking that really Angular needed middleware too ... and here it is ๐Ÿ‘ . I'd propose it be part of Angular core.

What I think the documentation lacks is ...

  • A demonstration of how to access the destination path or route. Often you want to apply an Aspect Oriented middleware rule that will include or exclude a pattern of route names or path names or parameter names. I'm not sure if params includes all of these so an example of how to do this would be very valuable.
  • You often want to apply this to an abstract ui route so that a whole set of sub routes will have consistent middleware injected. This is really just a specialization of the pattern case but I think this very common case needs an example. It was what I went hunting for first when I looked over your documentation.

Adding these powerful examples should really help sell your concept.

Angular 2

Hey!
Have you reached a verdict with Angular2 implementation of middlewares?

thanks

[ui-router] Redirect to child view infinite loop

One might want to set up a state to redirect to a sub-state using middleware.
Say, /docs always redirects to /docs/getting-started.

When a simple this.redirectTo('parent.child') middleware is written and called when routing to the parent state, it results in an infinite loop.

Example: (caution: crashes page)
https://plnkr.co/edit/syZdLJQ2I8ZomP7T9ndA?p=preview

In this example, there are state one with sub-states, one.one and one.two and state two. Presently, the only middleware used is one that simply calls this.next().

If one changes the middleware at the two lines commented with // Change to 'redirect' middleware to the redirect middleware, one expects that clicking the one and two links redirect to sub-state one.one. The two link performs as expected, but clicking the one link causes an infinite loop.

package on npmjs is not up to date

The repo on npm is out of date.

The redirectTo function in src/middleware.factory.js doesn't have params and options parameters. When install via npm the function has only route parameter available.

	/**
	 * Redirect to another route
	 *
	 * @returns {void}
	 */
	function redirectTo(route, params, options) {
		middleware.resolution.reject({
			type: "redirectTo",
			route: route,
			params: params,
			options: options
		});
	}

plugins.js:2 TypeError: Cannot read property 'next' of undefined

Hi,

I always get those error when setup the middleware. here is my code:

 $middlewareProvider.map({ 

            'check-token': ['Auth', (Auth) => {
                const request = this;
                Auth.get({ url: 'check-token' }, response => {
                    if (response) {
                        return request.next();
                    }
                });
            }]
        });

this.route is undefined

Hello,
Inside a middleware function, I tried to access 'this.route' and it gets undefined.
Tried this as saw in at the bottom of the documentation.

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.