[英]Angular 7 url routing configuration
我正在开发一个 angular 7 应用程序,我现在遇到了一个有趣的问题。
我的目标是不在整个应用程序中使用“硬编码 URL”。
所以,我有一种方法,比如维护一个单一的配置文件,我可以在其中拥有所有站点 URL 并提供所需的组件和模块。
具有如下代码的配置。
route.ts // 网址配置文件
import { LayoutComponent } from './layout/layout.component';
import { AdminIndexComponent } from './admin-index/admin-index.component';
import { AdminRegisterComponent } from './admin-register/admin-register.component';
import { LoginComponent } from './login.component';
export class AppRoutes {
// Angular components url
public static componentsUrl = {
base: {
path: '',
component: AdminIndexComponent,
pathMatch: 'full'
},
register: {
path: 'register',
component: AdminRegisterComponent
},
login: {
path: 'login',
component: LoginComponent
},
home: {
path: 'home',
component: LayoutComponent
}
};
路线-service.ts
import { Injectable } from '@angular/core';
import { AppRoutes } from './routes';
import { environment } from '../environments/environment';
@Injectable({
providedIn: 'root',
})
export class AppRouterService {
routesArray = [];
getAppRoutesArray() {
Object.entries(AppRoutes.componentsUrl).forEach(
([key, value]) => this.routesArray.push(value)
);
return this.routesArray;
}
}
app-routing.module
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AppRouterService } from './routes-service';
const routes: Routes = ;
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
在这个级别上一切都很好。 我可以提供路由的 URL。
但有趣的情况是,我有另一个需要 URL 的组件。
admin-index.component.ts
import { Component, OnInit } from '@angular/core';
import { RegistrationModule } from 'shared-components';
import { AppRouterService } from '../routes-service'; // Causing the circular dependency
@Component({
selector: 'app-admin-index',
templateUrl: './admin-index.component.html',
styleUrls: ['./admin-index.component.scss']
})
export class AdminIndexComponent implements OnInit {
appRoutesUrl;
constructor(private regModule: RegistrationModule, private routerService: AppRouterService) { }
ngOnInit() {
this.appRoutesUrl = this.routerService.getAppRoutesObject(); // This variable in binding to component html. So I can retrieve the url from config file
}
}
当我这样做时,我收到了一个警告,如“检测到循环依赖项中的警告”。 我知道在routes.ts上导入“ AdminIndexComponent ”会导致此警告。
我可以知道如何摆脱这个问题吗? 还请提出一种有效的方法来做到这一点?
谢谢你。
首先在 app.module.ts 中添加
import { RouterModule, Routes} from '@angular/router';`
然后添加这个进口,
RouterModule.forRoot(appRoutes)
之后,您可以在同一文件中创建如下所示的路由。
const appRoutes: Routes = [
{path: '', component:AdminIndexComponent},
{path: 'register', component:AdminRegisterComponent},
{path: 'login', component:LoginComponent},
{path: 'home', component:LayoutComponent}
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.