【发布时间】:2018-05-02 22:00:01
【问题描述】:
我有一个带有子模块和子路由的应用程序。 我需要安装一个服务来响应每一个路由器的变化。
我的问题是我找不到初始化它的方法。 Angular 模块没有 NgOnInit,我可以在其中传递路由器对象,RouterModule 也没有。
除非我在每个组件中将路由器传递给我的服务,否则我不知道如何解决这个问题。
另一个想法是使用守卫来设置路由器,但这似乎很脏,因为这不是守卫的用途。
【问题讨论】:
我有一个带有子模块和子路由的应用程序。 我需要安装一个服务来响应每一个路由器的变化。
我的问题是我找不到初始化它的方法。 Angular 模块没有 NgOnInit,我可以在其中传递路由器对象,RouterModule 也没有。
除非我在每个组件中将路由器传递给我的服务,否则我不知道如何解决这个问题。
另一个想法是使用守卫来设置路由器,但这似乎很脏,因为这不是守卫的用途。
【问题讨论】:
你不能在主组件中(通常在 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,它监听路由变化并采取相应的行动。
将此RouteService 注入app.component.ts。
不要忘记在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.
}
}
【讨论】:
app.component.ts 中注入此服务一次并在那里处理路由。