2

Use Case

The user can access certain parts of my site without being logged in. If they click a download button and are logged in, the download starts automatically. However, if they click the download button and are not logged in, I'd like to prompt them to login. Once they're logged in, I'd like them to be sent straight back to the route they were previously on.

How I'm trying to accomplish it

When an "anonymous" user clicks a download button, they're given a modal with a prompt to login. If they decide to login, I'll stash some object in local storage (was thinking an ActivatedRouterSnapshot would do?). After login, I'll check to see if there's an object stored under stashedRoute in local storage. If there is, I'll use it to navigate them back to their original route!

What I want to do

Given:

import { Router } from '@angular/router';

and

private someRoute: ActivatedRouterSnapshot;

constructor(private _router: Router) {}

I want to:

this._router.navigate(someRoute)

The question

What is the syntax for either doing the above, or getting the same functionality for storing a route and re-navigating to it?

Corbfon
  • 3,514
  • 1
  • 13
  • 24

2 Answers2

0

i think you need some thing like a history for going back in routes you can use code below as described here

import {Component} from '@angular/core';
import {Location} from '@angular/common';


@Component(...)

class AppCmp {
  constructor(private _location: Location) {
  }
  backClicked() {
    this._location.back();
  }
}
Community
  • 1
  • 1
Amir Ghezelbash
  • 2,195
  • 15
  • 24
  • This may work. The Angular 2 `Location` docs suggest that it is better to use the `router` service to trigger navigation. Surely there has to be a way to "save" a route for later navigation? – Corbfon Jan 18 '17 at 19:14
  • i have no idea, use session storage simply put the route in it then after redirecting back remove it – Amir Ghezelbash Jan 18 '17 at 19:22
  • Perhaps there's a way to get the `link parameters array` for the currently activated route? This would be the ideal, but I'm not sure if/how it is exposed – Corbfon Jan 18 '17 at 19:48
0

I had a similar issue and solved it by the following. flatten is from lodash and route is your ActivatedRoute. It's not great, but it works for now. You might want to use flattenDeep instead to accommodate for deeply nested routes.

const route = flatten(route.pathFromRoot.map(r => r.url)).map(s => s.path);
this.router.navigate(route);
altschuler
  • 3,694
  • 2
  • 28
  • 55