Andrea Reginato
Andrea Reginato

Reputation: 1338

Hash removed from default routing in AngularJS

I'm writing an angular app where I need to accept an URL with a fragment hash (OAuth 2.0). Making it short it looks like this.

http://example.com/#access_token=918f4d6e90b25b13ef66a

When this URI is loaded, the routing process does not recognize the path and and it correctly redirects the app to the default route. The problem is that in thi way I loose the hash and I can't parse it anymore.

What I want to do is to parse the hash before it gets removed. Do you have any idea on a possible solution?

Thanks.

P.S. In this app I can't use HTML5 mode. With it enabled it works just fine.

Upvotes: 0

Views: 179

Answers (1)

gkalpak
gkalpak

Reputation: 48211

You just need to define an extra route to "catch" and save the access-token, before redirecting to another route.
E.g.:

$routeProvider
    ...
    .when('/access_token=:accessToken', {
        template: '',
        controller: function ($location, $routeParams, AuthService) {
            AuthService.login(               // `AuthService` will save the token
                $routeParams.accessToken);   // The token is available in `$routeParams
                                             //     under the key `accessToken`
            $location.path('/');   // Redirect to the default route
            $location.replace();   // For better UX, remove this route from history
        }
    })

See, also, this short demo.

Or navigate directly to this URL for a live demo:
http://fiddle.jshell.net/ExpertSystem/N8CgC/show#access_token=12345.

Upvotes: 1

Related Questions