Angular IO 中根组件的查询参数

Query parameters for root component in Angular IO

我有一个非常简单的 Angular 4+ 应用程序,它从 API 获取数据并显示数据。我相信这应该可以通过仅使用根组件来实现:{path: 'main', component: MainComponent} 和 QueryParams,如 ?id=1

我能够获取查询参数,但由于某种原因,我的路由器在已经存在的路由+参数部分之后重复了 URL 的路由+参数部分。例如,我的本地地址从 localhost:4200/main?id=1 变形为 localhost:4200/main?id=1/main?id=1

ActivatedRoute 确实从 URL 中选择了正确的查询参数,但我希望尽可能保持 URL 的安全。如何防止这种重复发生?我在 index.html.

中根据路由要求设置了 <base href='/'>

模块:

@NgModule({
  imports: [
    BrowserModule,
    RouterModule,
    RouterModule.forRoot(
      [
        { path: 'main', component: MainComponent},
      ]),
    CommonModule,
    HttpModule,
    FormsModule,
    NgbModule.forRoot()
  ],
  declarations: [MainComponent],
  providers: [
    {provide: APP_BASE_HREF, useValue: window.document.location.href},
    DataService,
    WindowService,
    HttpUtil
  ],
  bootstrap: [MainComponent]
})
export class MainModule{}

组件:

@Component({
  selector: 'main-component',
  templateUrl: './main.component.html',
  styleUrls: ['./main.component.css']
})

export class MainComponent implements OnInit {

  constructor(private dataService: DataService,
              private activatedRoute: ActivatedRoute) {
  }

  ngOnInit() {
    this.activatedRoute.queryParams.subscribe((params: Params) => {
      if (!(Object.keys(params).length === 0 && params.constructor === Object)) {
        console.log(params);
      }
    });
  }
}

这是您的APP_BASE_HREF

造成的
{provide: APP_BASE_HREF, useValue: window.document.location.href}

您是在告诉应用程序使用 window.document.location.href main?id=1 作为您的 basehref。 Angular 然后将自己的路由附加到 basehref 的末尾。这就是为什么你得到重复

 localhost:4200/main?id=1(< APP_BASE_HREF)/main?id=1(< ROUTE)

这是关于 APP_BASE_HREF (https://angular.io/api/common/PathLocationStrategy#description)

功能的文档