我正在处理一个Range7应用程序,我现在正面临一个有趣的问题。
我的目标是在整个应用程序中不使用“硬编码URL”。
因此,我有一种方法,比如维护一个配置文件,其中我可以拥有所有的站点URL,并提供所需的组件和模块。
具有类似于以下代码的配置。
routes.ts // Url配置文件
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。
但有趣的是,我还有另一个组件需要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
}
}当我这样做的时候,我收到了一个类似于“检测到循环依赖项中的警告”的警告。我知道"AdminIndexComponent“在routes.ts上的导入导致了这一警告。
我能知道如何处理这个问题吗?另外,请提出一个有效的方法来做这件事?
谢谢。
发布于 2019-03-12 04:00:06
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}
]https://stackoverflow.com/questions/54034590
复制相似问题