使用路由器插座的正确方法是什么?

时间:2019-08-19 16:01:00

标签: angular angular2-routing

我正在构建一个类似Reddit的测试应用程序来练习Angular,对于我一生来说,我不知道如何正确使用路由器插座。我认为这可能是有问题的,因为我没有导航到其他组件,我想在URL中使用一个参数来显示相同​​的组件(帖子列表),但是根据该参数进行了过滤(该过滤条件是)。

我一直在两个问题之间跳来跳去,这些问题可以单独解决,但不能同时解决:

如果我像这样使用路由器插座,则会得到我想要的参数,但应用会启动两次(然后移动路由器插座标签使页面具有重复的渲染):

app.component.html:

<mat-toolbar color="warn">
 <span> {{ title }}</span>
</mat-toolbar>
<app-posts-list [posts]="currentPosts">
  <router-outlet></router-outlet>
</app-posts-list>

如果我删除router-outlet标记,则该应用仅启动一次(应如此),但是如果直接导航到该参数,则无法从URL获取参数(未定义)(我没有尝试导航)在应用程序中使用该参数,则无论如何应通过直接URL来使其正常工作)

app.component.ts:

this.route.paramMap.subscribe(params => {
  this.currentSub = params.get("subname");
});

最重要的是(可能相关,也许不相关),我尝试通过URL参数过滤的帖子列表永远不会根据发送应用程序的参数进行更新。它仅适用于第一个ngOnInit。

更多可能有用的代码:

app-routing-module.ts(有人告诉我,无需定义到AppComponent的默认路由,因为这是Angular的默认路由):

const routes: Routes = [
  { path: "r/:subname", component: AppComponent },
  { path: "**", component: AppComponent }
];

app.component.ts:

currentPosts: Array<Post>;
currentSub: string;

constructor(
  private postService: PostService,
  private route: ActivatedRoute
) {}

ngOnInit() {
  this.route.paramMap.subscribe(params => {
    this.currentSub = params.get("subname");
  });
  if (this.currentSub) {
    this.getSubPosts(this.currentSub);
  } else {
    this.getPosts();
  }
}

getPosts(): void {
this.postService.getPosts().subscribe(posts => (this.currentPosts = posts));
}

getSubPosts(subName): void {
this.postService
  .getSubPosts(subName)
  .subscribe(posts => (this.currentPosts = posts));
}

post.service.ts:

getPosts(): Observable<Post[]> {
  return of (POSTS);
}

getSubPosts(subname): Observable<Post[]> {
  return of (POSTS.filter(post => post.sub == subname));
}

最终,我很高兴在这里了解正确的实现方式,因为我感觉自己事情变得复杂了,挖了个小洞。

0 个答案:

没有答案