【问题标题】:Query parameters for root component in Angular IOAngular IO 中根组件的查询参数
【发布时间】:2018-04-26 05:02:58
【问题描述】:

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

我能够获取查询参数,但由于某种原因,我的路由器在已经存在的 route+params 部分之后重复了 URL 的 route+params 部分。例如,我的本地地址从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);
      }
    });
  }
}

【问题讨论】:

    标签: angular angular2-routing angular4-router


    【解决方案1】:

    这是由您的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) 功能的文档

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-21
      • 2018-11-10
      • 2018-03-20
      • 2019-02-02
      • 2021-11-27
      • 1970-01-01
      • 1970-01-01
      • 2016-12-10
      相关资源
      最近更新 更多