我有一个非常简单的Angular 4应用程序,它从API获取数据并显示数据 . 我相信这应该只使用根组件: {path: 'main', component: MainComponent}
和QueryParams,如 ?id=1
.
我能够获取查询参数,但由于某种原因,我的路由器在已经存在的路由参数部分之后重复路由params部分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);
}
});
}
}
1 回答
这是由你
APP_BASE_HREF
引起的您告诉应用程序使用window.document.location.href
main?id=1
作为您的basehref . 然后Angular将自己的路由附加到basehref的末尾 . 这就是你获得重复的原因以下是有关APP_BASE_HREF(https://angular.io/api/common/PathLocationStrategy#description)功能的文档