简体   繁体   English

使用Angular 2 RC5路由器,给定ActivatedRouteSnapshot,如何导航?

[英]Using Angular 2 RC5 router, how can I navigate, given an ActivatedRouteSnapshot?

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?). 如果他们决定登录,我会将一些对象存储在本地存储中(正在考虑使用ActivatedRouterSnapshot可以做什么?)。 After login, I'll check to see if there's an object stored under stashedRoute in local storage. 登录后,我将检查本地存储中是否在stashedRoute下存储了一个对象。 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? 进行上述操作或获得与存储路线并重新导航至该路线相同的功能的语法是什么?

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();
  }
}

I had a similar issue and solved it by the following. 我有一个类似的问题,并通过以下方法解决了。 flatten is from lodash and route is your ActivatedRoute. flatten来自lodash,而route是您的ActivatedRoute。 It's not great, but it works for now. 这不是很好,但目前可以使用。 You might want to use flattenDeep instead to accommodate for deeply nested routes. 您可能想使用flattenDeep来容纳深度嵌套的路由。

const route = flatten(route.pathFromRoot.map(r => r.url)).map(s => s.path);
this.router.navigate(route);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM