监听多个路由器

Listen to multiple routers

我有一个带有子模块和子路由的应用程序。 我需要安装一个对每个路由器更改做出反应的服务。

我的问题是我找不到初始化它的方法。 Angular 模块没有 NgOnInit,我可以在其中传递路由器对象,RouterModule 也没有。

除非我在每个组件中将路由器传递给我的服务,否则我不知道如何解决这个问题。

另一个想法是使用 guards 来设置路由器,但这看起来很脏,因为这不是 guards 的目的。

你不能在主组件中注入路由器(通常在app.component.ts中)然后订阅它的事件吗?

export class AppComponent {
   constructor(private router: Router) {}

   ngOnInit() {
      this.router.events.subscribe( event => {
        //here you will have an event, such as NavigatiunStart, NavigationEnd, etc...
      })
   }
}

有一个路由服务 RouteService,它监听路由变化并相应地采取行动。 在 app.component.ts 中注入此 RouteService。 不要忘记在 app.module.ts.

中提供服务

因为此服务只有一个实例。你可以用它来挂钩路由更改

@Injectable()
export class RouteService {
constructor(public router: Router) {
    // this.initialize();  // You can initialize from here or from app component
}

initialize() {
    this.router.events.filter((event) => event instanceof NavigationEnd).subscribe((event: any) => {
        this.onRouteChange(event);
    });
}
onRouteChange() {
   // Handle route change.
}
}

注入 app.component.ts

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.scss"]
})
export class AppComponent implements OnInit {
   constructor(
       public routeService: RouteService) {
   }
   ngOnInit(): void {
    this.routeService.initialize(); // Intitialize here.
  }
}