【问题标题】:Angular routing/switch components without page reload无需重新加载页面的角度路由/切换组件
【发布时间】:2020-06-26 20:57:32
【问题描述】:

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

<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】:

你在这里写的代码是一个反模式:

<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 并发送请求(考虑到您有一个SearchServicesearch 方法:

this.activatedRoute.queryParams
    .pipe(switchMap(params => this.searchService.search(params['query'])))
    .subscribe(result => this.result = result);

【讨论】:

  • 对不起,我的代码的意思是,我确实在路由器组件中有搜索结果和用户,但我宁愿跳过路径,只根据具体情况切换组件我做了什么样的请求,得到什么样的回应
  • 为此,请根据入站路由使用 ngif。一次只显示一件事。还有其他方法,例如在需要时使用一个外部视图范围进行渲染。
猜你喜欢
  • 2021-11-27
  • 1970-01-01
  • 2018-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多