繁体   English   中英

如何重定向到angular2中不同组件的后退按钮单击上的页面?

[英]How to redirect to the pages on back button click of different components in angular2?

我有3页来实现这种情况。

目前,

  1. 如果我转到第一页,请单击以导航到第二页。 然后,在第二页上,单击“后退”按钮。 它工作正常(即,导航到第一页)。

  2. 现在,从第一页转到第二页,然后单击以导航到第三页。 然后,在第三页中,我单击“后退”按钮,它会按预期重定向到第二页。

现在,如果我单击第二页上的后退按钮,它将再次转到第三页。 我希望将其重定向到第一页。

在这里,实际上根据代码,它工作正常,但我的要求是

  1. 我有2页company和companyApp,其中两个页面都有相同的指南和图钉页面。所以,我想将指南页面重定向到公司页面,即使我曾经从公司页面访问指南页面,即使指南页面来自图片页面。

  2. 如果我曾经从compnay应用程序页面引导页面,那么它必须重定向到公司应用程序页面,即使它又被定向到图像页面和所有页面。

因此,任何人都可以帮助我解决此问题:

TS:

// 1st Page:
goToGuide1(company){
  this.router.navigate(['/guide',company.user._id]);
}

// 2nd page:
import {Location} from '@angular/common';
constructor(private _location: Location) {}
goToCompany1() {
  this._location.back();
}

goImg(guide) {
  this.router.navigate(['/guideimg', guide._id]);
}

// 3rd page
goToGuide1() {
  this.router.navigate(['/guide',this.user_id])
}

在第二页上:如果我进入“图像”页并单击“后退”按钮,它会进入指南页面,但不会进入第一页。

出现这种情况的原因:发生这种情况的原因是第三页存储在location属性中。

Angular API文档指出,

“注意:最好使用路由器服务来触发路由更改。仅当您需要在路由之外与之交互或创建标准化URL时,才使用位置。”

您可能遇到的问题的解决方案是,

  1. 编写一项服务,将整个用户导航历史记录保存到数据结构中,并在需要时进行检索。

  2. 通过查询参数附加重定向状态,以便使用条件语句可以在当前页面上进行检查。

如果我在整个应用程序中有几次相同的行为,我可能会选择选项1。 但是这里第二个选项可以。

从任何页面重定向时,将页面详细信息添加到queryParams中并进行重定向。

例如-如果来自公司页面,

[routerLink]="['/guide', <anyId>]" [queryParams]="{from: 'company'}"

 or

goToGuide1(company){
  this.router.navigate(['/guide',company.user._id], { queryParams: { 'from': 'company' } });
}

因此,当您重定向回后方时,可以检查条件并重定向回去。

// Import
import { ActivatedRoute } from '@angular/router';

// Inject
constructor(
  private route: ActivatedRoute
) {
  // store the previous state
  this.route.queryParams.subscribe(params => {
    this.redirectedFrom = params['from'];
  }
}

// check the condition while redirect
goToBackState() { // can go as goToCompany
  if (this.redirectedFrom === company) {
    // redirect to company
  } else {
    // otherwise redirect to companyApp
    // Please note that you can check for the companyApp as well.
  }
}

这与如何处理条件逻辑和整体逻辑有关。 如果您确定了这些并正确地进行了处理,则它应该可以正常工作。

我们使用localStorage并存储当前Component并相应地重定向,

既然有

{ path: 'company', component: CompanyComponent, canActivate:[AuthGuard] },
{ path: 'companyapp', component: CompanyAppComponent, canActivate:[AuthGuard] }

在公司组件中:

goToGuide(company){
  this.localStorage.store('oldroute', 'company')
  this.router.navigate(['/guide',company.user._id]);
}

在companyApp组件中:

goToGuide(company){
  this.localStorage.store('oldroute', 'companyapp')
  this.router.navigate(['/guide',company.user._id]);
}

在向导组件中,

goToCompany() {
  if(this.localStorage.retrieve('oldroute') && (this.localStorage.retrieve('oldroute') == 'companyApp'))
  {
    this.router.navigate(['/companyApp']);
  }else{
    this.router.navigate(['/company']);
  }
}

暂无
暂无

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

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