網站搜尋

angular - ActivatedRoute 在服務中無法使用


服務中的 ActivatedRoute

問題

我嘗試在一個服務中使用 ActivatedRoute,但發現它似乎沒有追蹤我當前所在的路由。事實上,它似乎無法捕捉到任何路由。我花了很長時間才弄清楚發生了什麼,而且在網上幾乎找不到有用的答案(可能是因為大多數人比我快很多 :))。

只是想確保我發佈了一些內容,這樣其他人可以更快地找到解決方案。

當我遇到這個問題時,我的程式碼是這樣的。

@Injectable()
export class ImdbService {

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

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

答案#1

我的解決方案

因為當作為服務注入時,服務似乎與 ActivatedRoute 的互動不像組件那樣,所以我的解決方案是將 ActivatedRoute 作為參數傳遞給我正在使用的服務調用。

這就是對我有效的解決方案的樣子:

@Injectable()
export class ImdbService {

  constructor(private router: Router) {
  }

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

在組件中:

export class MovieDetailsComponent implements OnInit, OnDestroy {

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

  closeDetails() {
    this.imdbService.closeDetails(this.route);
  }

有更好的嗎?

如果有人對這個問題有更好或僅僅不同的解決方案,或者有充分的理由以完全不同的方式來做這件事,我很想看到它。

答案#2

直接在組件中注入你的服務

@Component({
  ...
  providers: [ImdbService], // provide your service here so it will be instanciated with your component.
})

export class MovieDetailsComponent implements OnInit, OnDestroy {

  constructor(..., private imdbService: ImdbService ) { }

  closeDetails() {
    this.imdbService.closeDetails();
  }