路由器angular2不适用于同一组件,但difefrenet ID

Oleksii Kryzh

我仍在使用alpha8路由器。我有3条主要路线:

export const appRoutes: RouterConfig = [
    { path: '', component: LandingComponent },
    { path: 'blog', component: BlogComponent },
    { path: 'posts/:id', component: PostComponent },
    { path: 'posts',  redirectTo: 'blog' },
    { path: '**', redirectTo: ''}  
];

因此,我有一个带有特色帖子和链接的组件,从BlogComponent那里可以很好地工作,但是当此组件位于PostComponent中时,id仅会更改网址。这就是链接在该组件中的样子

<a [routerLink]="['/posts/'+post.id]">...</a>

因此,当我们localhost:5000/blog到达localhost:5000/posts/19目的地时,可以很好地到达f.ex。但是从localhost:5000/posts/19它不会去localhost:5000/posts/20它只是改变了URL, contstructorngOnInit不执行。我怎么解决这个问题?

mpilliador

您必须在ngOnInit内添加一个“ subscriber”以捕获url参数中的更改。另外,您应该在ngOnDestroy内退订(与OnInit一样,将其实现到组件类中),以避免内存泄漏。

import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
    selector: 'your-posts-component'
})
export class PostsComponent implements OnInit, OnDestroy {

private sub: any;

constructor(private route: ActivatedRoute ) {}

// add a subscriber to watch for changes in the url
ngOnInit() {
    this.sub = this.route.params
       .subscribe(params => {
          // get id from params
          let id = +params['id'];

          // do whatever you want with id here

        });
      }
}

// unsubscribe to avoid memory leaks
ngOnDestroy() {
    this.sub.unsubscribe();
}

当重新访问一个组件而不通过另一个组件时,这就是如何检测url参数的更改。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章