我正在开发一个angular 7应用程序,在那里我现在面临着一个有趣的问题。
我的目标是在整个应用程序中不使用“硬编码URL”。
因此,我有一种方法,例如维护一个配置文件,使我可以拥有所有站点URL,并提供所需的组件和模块。
具有类似以下代码的配置。
routes.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
}
};
routes-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的组件。
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
}
}
在执行此操作时,我收到类似“ 检测到循环依赖项的警告”的警告。我知道在route.ts上导入“ AdminIndexComponent ”会导致此警告。
我可以知道如何摆脱这个问题吗?还请提出一种有效的方法来做到这一点?
谢谢。
答案 0 :(得分:1)
首先在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}
]