我在我的Angular 应用程序中有一个导航服务,它在开发模式下工作得很好,但是一旦完成了生产构建,它就停止工作了.
该服务很简单;它返回当前活动的组件,但在生产中,它只返回‘a’.
以下是服务代码:
@Injectable({
providedIn: 'root'
})
export class NavigationService {
private activeComponentSubject: BehaviorSubject<string> = new BehaviorSubject<string>('');
constructor(private router: Router, private route: ActivatedRoute) {
this.subscribeToNavigationEnd(this.route);
}
private subscribeToNavigationEnd(route: ActivatedRoute): void {
this.router.events.pipe(
filter(event => event instanceof NavigationEnd)
).subscribe((event: NavigationEnd) => {
const activeComponent = this.getActiveComponent(route);
this.activeComponentSubject.next(activeComponent);
});
}
private getActiveComponent(route: ActivatedRoute): string {
const childRoute = route.firstChild;
if (childRoute) {
return this.getActiveComponent(childRoute);
} else {
const componentName = route.outlet === PRIMARY_OUTLET ? route.component?.['name'] : '';
return componentName || '';
}
}
getComponent(): BehaviorSubject<string> {
return this.activeComponentSubject;
}
}
在组件中,它的名称是这样的:
ngOnInit(): void {
this.navigationSubscription = this.navigation.getComponent().subscribe(component => {
this.setPath(component);
console.log(component);
});
}
如果我在开发中打开组件,我会得到ShopComponent、CheckoutComponent等值.
而在制作过程中,我只得到了‘a’.
以下是angular.json
配置:
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"namedChunks": false,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,
"budgets": [
{
"type": "initial",
"maximumWarning": "2mb",
"maximumError": "5mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "6kb",
"maximumError": "10kb"
}
],
"serviceWorker": true,
"ngswConfigPath": "ngsw-config.json"
},
"development": {
"buildOptimizer": false,
"optimization": false,
"vendorChunk": true,
"extractLicenses": false,
"sourceMap": true,
"namedChunks": true
}
}