根据Angular版本不同,可能需要不同的解决方法。以下是两种可能的解决方式:
在组件中注入Router,而不是Location。然后使用navigate
方法来改变URL。
import { Router } from '@angular/router';
constructor(private router: Router) {}
goToRoute(route: string): void {
this.router.navigate([route]);
}
在组件中注入Location,并使用ngZone.run()
将变化应用于Angular应用程序。然后使用go
方法来改变URL。
import { Location } from '@angular/common';
import { NgZone } from '@angular/core';
constructor(private location: Location, private ngZone: NgZone) {}
goToRoute(route: string): void {
this.ngZone.run(() => {
this.location.go(route);
});
}