Angular 获取 URL 参数无法正常工作

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

我需要检索 URL 查询,如

www.website.com?a:b
中所示。 为此,我遵循了这个官方角度教程,引导我在组件中找到这个简单的代码:

constructor(private route: ActivatedRoute) {}

ngOnInit() {
  this.route.queryParams.subscribe(params => {
    console.log(params)
  })
}

这会在控制台中触发以下错误:

错误NullInjectorError:R3InjectorError(AppModule)[ActivatedRoute->ActivatedRoute->ActivatedRoute]: NullInjectorError:没有ActivatedRoute的提供者!

虽然教程中没有提及事件,但我将

ActivatedRoute
添加到我的
app.module.ts
中。这会产生不同的错误:

错误:NG0204:无法解析 ActivatedRoute 的所有参数:(?, ?, ?, ?, ?, ?, ?, ?)。

我不知道为什么没有其他人遇到这个问题,有谁知道问题可能是什么?谢谢。

angular typescript
3个回答
1
投票

很可能在您的 app.module 或 main.module 文件中您需要添加导入。 如果您查看位于所链接页面底部的此链接,您会看到

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    // This is what provides the ActivatedRoute service
    // You likely don't need useHash: true, so you can leave it out
    RouterModule.forRoot(routes, { useHash: true })  // .../#/crisis-center/
  ],
  declarations: [
    AppComponent,
    PageNotFoundComponent
  ],
  providers: [

  ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

1
投票

这就是为什么我更喜欢直接在路由中使用参数。

应用程序路由.modules.ts

{ path: 'bible/:bookId/:chapterId/:verseIdStart/:verseIdEnd', component: BibleComponent },

圣经.component.ts

  constructor(
    private route: ActivatedRoute,
  ) {
    const bookId: number = Number(this.route.snapshot.params.bookId) || 0;
    const chapterId: number = Number(this.route.snapshot.params.chapterId) || 0;
    const verseIdStart: number = Number(this.route.snapshot.params.verseIdStart) || 0;
    const verseIdEnd: number = Number(this.route.snapshot.params.verseIdEnd) || 0;
  }


0
投票

我认为您想要实现的目标可能如下所示:

this.sub = this.activatedRoute.params.subscribe((params : Params) => {
    // You now have all params in a single variable 'params'
});
© www.soinside.com 2019 - 2024. All rights reserved.