angular 判断路由是否存在,不存在跳到404,存在就跳到相应路由
时间: 2023-02-07 11:45:33 浏览: 95
你可以使用 Angular 的 Router 类的 navigate 方法来跳转到另一个路由。你可以使用 Router 类的 url 方法来获取当前路由的 URL。你可以在你的路由配置中设置一个通配符路由,用来匹配所有无法匹配到其它路由的 URL。然后你就可以在通配符路由的组件中处理 404 错误。
示例代码:
```
import { Router } from '@angular/router';
@Component({
// 省略其它代码
})
export class MyComponent {
constructor(private router: Router) { }
checkRouteExistence(routeUrl: string) {
const currentUrl = this.router.url;
if (currentUrl === routeUrl) {
// 当前路由存在
// 你可以在这里做一些其它的处理
} else {
// 路由不存在,跳转到 404 页面
this.router.navigate(['/404']);
}
}
}
```
相关问题
angular 浏览器刷新时,默认跳到loading页面,发果路由不存在跳到404
在 Angular 中,当浏览器刷新时,默认会跳到 loading 页面。如果发现路由不存在,就会跳到 404 页面。
你可以在 Angular 应用的路由模块中配置这些路由,并在应用的组件中实现对应的视图。
例如,你可以在路由模块中使用如下代码来配置 loading 和 404 页面:
```
const routes: Routes = [
{ path: 'loading', component: LoadingComponent },
{ path: '404', component: PageNotFoundComponent },
// 其他路由
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
```
然后,你就可以在组件的模板中使用路由指令来显示这些页面,例如:
```
<router-outlet></router-outlet>
```
这样,当用户浏览到对应的路由时,就会显示对应的组件。
angular 如何判断路由是否存在
在 Angular 中,你可以使用 `Router.navigateByUrl()` 方法来判断路由是否存在。
```
import { Router } from '@angular/router';
constructor(private router: Router) {}
checkRouteExists(route: string) {
return this.router.navigateByUrl(route).then(() => true).catch(() => false);
}
```
在这个例子中,你可以传入路由路径的字符串,然后使用 `navigateByUrl()` 方法尝试导航到该路由。如果导航成功,则返回 `true`,否则返回 `false`。
注意:这个方法并不能判断路由是否有效,因为如果路由不存在也会返回 `false`。