ActivatedRoute在服务中不起作用

Dav*_*ter 5 dependency-injection typescript angular

服务中的ActivatedRoute

问题

我试图在服务中使用ActivatedRoute,但发现它似乎没有在跟踪我当前所在的路线。实际上,它似乎不会采取任何措施。我花了很长时间才弄清楚发生了什么,而且我无法在网上找到许多有用的答案(可能是因为大多数人都比我快很多:)

只是想确保我发布了一些内容,以便其他人可以更快地找到解决方案。

这是我遇到问题时的代码。

@Injectable()
export class ImdbService {

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

  closeDetails(): void {
    this.detailsOpened = false;
    this.router.navigate(['../'], {relativeTo: this.route});
  }
Run Code Online (Sandbox Code Playgroud)

Dav*_*ter 8

我的解决方案

因为当注入组件时,服务似乎与 ActivatedRoute 没有相同的交互,所以我的解决方案是将 ActivatedRoute 作为参数传递给我正在使用的服务调用。

以下是对我有用的解决方案:

@Injectable()
export class ImdbService {

  constructor(private router: Router) {
  }

  closeDetails(currentRoute): void {
    this.detailsOpened = false;
    this.router.navigate(['../'], {relativeTo: currentRoute});
  }
Run Code Online (Sandbox Code Playgroud)

在组件中:

export class MovieDetailsComponent implements OnInit, OnDestroy {

  constructor(..., private route: ActivatedRoute ) { }

  closeDetails() {
    this.imdbService.closeDetails(this.route);
  }
Run Code Online (Sandbox Code Playgroud)

有更好的吗?

如果有人对这个问题有更好的甚至只是不同的解决方案,或者有充分的理由以完全不同的方式来解决这个问题,我很乐意看到它。

  • @NicoTimmerman 在任何实际情况下,应用程序路由都不是表示层(组件)的责任。即使只是从可重用性的角度来看,组件也不应该关心它们或整个应用程序的路由方式。 (2认同)