无需重新加载页面的角路由/交换机组件

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

这是我所拥有的非常基本的设置,

<app-header></app-header>
<app-search></app-search>
<router-outlet></router-outlet>
<app-footer></app-footer>

并且在路由器出口内,我有一个搜索结果组件和一个用户组件

像这样

const routes: Routes = [
    { path: 'search', component: SearchResultComponent },
    { path: 'user', component: UserComponent}
];

我使用路由器,角形核心的路由器模块,并在其中包含搜索结果和用户,以及路径搜索和用户

[如果可能的话,我想一起跳过所有路径,一旦我在应用搜索中搜索某些内容并按下Enter键,然后从服务器获得响应,路由器插座将仅显示搜索结果组件,而无需重新加载页面

angular angular-router
1个回答
0
投票

您在此处编写的代码是反模式:

<router-outlet>
  <search-result></search-result>
  <user></user>
</router-outlet>

RouterOutlet指令不包含任何内容。它只是路由加载的组件的占位符。

如果要实现这一点,必须定义路线。 SearchComponent会触发,例如this.router.navigate(['search'], { queryParams: { query: 'what your used typed' } });

然后定义到SearchResultComponent的路线:{ path: 'search', component: SearchResultComponent }

最后,在SearchResultComponent中,订阅queryParams并发送一个请求(考虑到您使用SearchService方法拥有一个search

this.activatedRoute.queryParams
    .pipe(switchMap(params => this.searchService.search(params['query'])))
    .subscribe(result => this.result = result);
© www.soinside.com 2019 - 2024. All rights reserved.