Angular v17 错误:NullInjectorError:没有ActivatedRoute 的提供者

问题描述 投票:0回答:1

我正在创建一个 Angular 项目并出现以下错误,这使得我的页面无法加载: 错误 NullInjectorError:R3InjectorError(独立 [_AppComponent])[ActivatedRoute -> ActivatedRoute -> ActivatedRoute]: NullInjectorError:没有ActivatedRoute的提供者!

由于它是 Angular v17,所以我上面没有 AppModule。 这是我的以下代码:

app.config.ts

import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';

import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {
  providers: [provideRouter(routes)]
};

app.component.ts

import { Component, LOCALE_ID } from '@angular/core';
import { registerLocaleData } from '@angular/common';
import { RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router';
import { SharedModule } from './shared/shared.module';
import localePT from '@angular/common/locales/pt';

registerLocaleData(localePT);
@Component({
  selector: 'app-root',
  standalone: true,
  imports: [SharedModule, RouterOutlet, RouterLink],
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [{provide: LOCALE_ID, useValue: 'pt-br'}]
})
export class AppComponent {
  title = "app";
}

app.routes.ts

import { Routes } from '@angular/router';
import { HomeComponent } from './features/pages/home/home.component';

export const routes: Routes = [
    { path: 'home', component: HomeComponent },
    { path: '', redirectTo: 'home', pathMatch: 'full' }
];

提前谢谢您!

我尝试在AppComponent中添加RouterModule.forRoot(routes),但没有成功。 我尝试在 AppComponent 上导入ActivatedRoute,但它引发了另一个错误:错误错误:NG0204:无法解析ActivatedRoute的所有参数:(?,?,?,?,?,?,?,?)。 我还尝试在 AppComponent 中导入 ActivateRoute,如下所示,但它返回: ERROR 错误:NG04002:无法匹配任何路由。 URL 段:'home'

import { Component, LOCALE_ID } from '@angular/core';
import { registerLocaleData } from '@angular/common';
import { ActivatedRoute, RouterLink, RouterOutlet } from '@angular/router';
import { SharedModule } from './shared/shared.module';
import localePT from '@angular/common/locales/pt';
import { routes } from './app.routes';

registerLocaleData(localePT);
@Component({
  selector: 'app-root',
  standalone: true,
  imports: [SharedModule, RouterOutlet, RouterLink],
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [{provide: LOCALE_ID, useValue: 'pt-br'}, **{provide: ActivatedRoute, useValue: routes}**]
})
export class AppComponent {
  title = "Rango's WEEK";
}

由于 Angular v17 没有 AppModule 并且不需要它,所以我没有创建它。

我希望我的页面能够正确加载,但它不允许它加载。

angular angular17 angular-activatedroute
1个回答
1
投票

你定义了appConfig,但是你使用它吗?你的 main.ts 是什么样的?它应该引导应用程序并使用您的 appConfig 提供程序:

bootstrapApplication(AppComponent, {
  providers: [...appConfig.providers, <your other providers>],
});
© www.soinside.com 2019 - 2024. All rights reserved.