在我的Angular 7项目中,我想有一个文件“ pages.ts”,在其中导出应用程序要具有的路线。这些由“ app-routing.ts”导入,以供RouterModule使用,也由“ pages.service.ts”导入,我要在其中管理这些路由的数据。现在,在我的组件“ test-one.component.ts”中,我想使用该服务“ pages.service.ts”,以便例如通过路径或标题获得路线的数据。一切正常,但出现此警告。
检测到循环依赖中的警告:src / app / pages / test-one / test-one.component.ts-> src / app / core / services / pages.service.ts-> src / app / core / constants / pages.ts-> src / app /pages/test-one/test-one.component.ts
“ pages.ts”
import { Page } from '../../core/models/page.model';
import { LoginComponent } from '../../pages/login/login.component';
import { SignupComponent } from '../../pages/signup/signup.component';
export const routePages: Page[] = [
{
path: '',
redirectTo: 'login',
pathMatch: 'full'
},
{
path: 'login',
component: LoginComponent,
canActivate: [],
data: {
title: 'Login',
description: '',
keywords: '',
icon: 'fingerprint',
hasBreadcrumb: true
},
pathMatch: 'full'
},
{
path: 'sign-up',
component: SignupComponent,
canActivate: [],
data: {
title: 'Sign up',
description: '',
keywords: '',
hasBreadcrumb: true
},
pathMatch: 'full'
}
];
“ app-routing.module.ts”
import { routePages } from './core/constants/pages';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
@NgModule({
imports: [RouterModule.forRoot(routePages, { scrollPositionRestoration: 'enabled' })],
exports: [RouterModule]
})
export class AppRoutingModule { }
“ pages.service.ts”
import { routePages } from './../constants/pages';
import { Page, PageData } from './../models/page.model';
import { Router } from '@angular/router';
import { Injectable, EventEmitter } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class PagesService {
pages = routePages;
private pagesChanged: EventEmitter<Page[]> = new EventEmitter<Page[]>();
constructor(private location: Location, private router: Router) {
this.setPagesFullPath();
console.log(this.pages);
}
.
.
.
}
“ test-one.component.ts”
import { Page, PageData } from './../../core/models/page.model';
import { PagesService } from './../../core/services/pages.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-test-one',
templateUrl: './test-one.component.html',
styleUrls: ['./test-one.component.scss']
})
export class TestOneComponent implements OnInit {
testATwoPage: Page;
constructor(private pagesService: PagesService) {
}
ngOnInit() {
this.testATwoPage = this.pagesService.getPageByTitle('Test A two');
}
}
我很想知道如何解决这种循环依赖性而不必放弃任何功能。
提前感谢!
我不知道PageService的目的是什么,但我认为那是错误的。要访问路由器的数据,您应该使用路由器事件或ActivatedRoute,然后执行所有操作。例如,在这段代码中,我从路线中获取要在面包屑中使用的信息:
this.router.events
.pipe(
filter(event => event instanceof NavigationEnd),
map(() => {
return this.getFirstChild(this.route.firstChild);
})
)
.subscribe(child => {
const title = child.snapshot.data['title'];
const previous = child.snapshot.data['previous'];
const parentUrl = child?.snapshot.parent?.url;
...
})