【问题标题】:Router angular2 does not work with the same component but difefrenet id路由器角度 2 不适用于相同的组件但不同的 id
【发布时间】:2016-09-04 14:20:15
【问题描述】:

我仍在使用 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 只会更改 url 地址。 这就是该组件中链接的样子

<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 不会被执行。我该如何解决这个问题?

【问题讨论】:

    标签: angular typescript angular2-routing


    【解决方案1】:

    你必须在 ngOnInit 中添加一个“订阅者”来捕捉 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 参数的变化的。

    【讨论】:

      【解决方案2】:

      onSameUrlNavigation 选项设置为reload

        imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: 'reload'})],
      

      【讨论】:

        猜你喜欢
        • 2019-07-04
        • 2018-09-19
        • 1970-01-01
        • 2021-04-22
        • 2017-04-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多