我正在开发一个 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
}
};
路线服务.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;
}
}
应用程序路由模块
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 的组件。
管理索引.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 ”会导致此警告。
我可以知道如何摆脱这个问题吗?还请提出一种有效的方法来做到这一点?
谢谢你。