首页 > 解决方案 > 如何从 Angular 12 应用程序中的辅助路线返回

问题描述

我有一个 Angular 12 应用程序,它在左侧显示事物列表,在右侧显示所选事物的详细信息。因为用户应该能够获得指向特定事物的深层链接,所以选择是通过 Angular 路由器完成的。这部分可以很容易地完成,并且有很多例子可以实现这一点。

该应用程序还有一个模态,例如,创建一个新事物,对于这个模态,应用程序使用辅助路由,以便外部站点可以直接链接到它。

截屏

起初,我对生成的 URL 感到困惑,例如,当我打开模式时,我得到

gb/en_GB/(layout/1//modal:new)

,但是选择具有打开模式的项目工作正常,这似乎是 Angular 路由器从 URL 树构造 URL 的方式。

什么不起作用是一旦打开模式就关闭它。我目前正在尝试通过将modal插座设置为来实现这一点,null但它不起作用:

@Component({
  selector: 'app-modal',
  templateUrl: './modal.component.html',
  styleUrls: ['./modal.component.css']
})
export class ModalComponent {
  showCloseButton = false;

  constructor(private router: Router, private route: ActivatedRoute) {}

  activate(active: boolean) {
    this.showCloseButton = active;
  }

  close() {
    this.router.navigate([{ outlets: { modal: null } }], {
      replaceUrl: true
    });
  }
}

我也有一个带有完整示例的Stackblitz 。

问题

  1. 如何关闭模式?
  2. 之后是否可以有一个“干净”的 URL(不带括号),即gb/en_GB/layout/1

标签: angularangular-routerangular-auxiliary-routes

解决方案


经过反复试验,我发现我必须使用relativeTo. 在这种情况下,它是

close() {
  this.router.navigate([{ outlets: { modal: null } }], {
    replaceUrl: true,
    relativeTo: this.route.parent
  });
}

它将modal: null相对于当前路由的父级(带有RootComponent)的路由应用增量。


推荐阅读