首次点击后Angular 2 routerLink不刷新组件,但浏览器中的URL正在更改

时间:2017-06-16 12:23:46

标签: angular angular2-routing

在Angular 2中,当我点击位于App模块上的routerLink时,它成功导航到参数化路线(例如/ events / 2)并在第一次点击时加载正确的组件(事件详情) 。但是,当我单击另一个链接(后续匹配(/ events / 3)时,它无法触发并刷新事件详细信息组件。

导航栏-component.html

这些链接仅适用于第一次点击!后续点击不会重新加载事件详细信息组件

注意链接2:它调用组件上的一个函数。对.navigate的调用与上面的效果相同 - URL已更改,但不是组件!该组件仅在第一次点击时触发!

<div><a [routerLink]="['/events/1']" routerLinkActive="active">Link 1</a></div>
<div><a (click)="onLinkClick(2);">Link 2 (Calls this.route.navigate on component</a></div>
<div><a [routerLink]="['/events', 3]" routerLinkActive="active">Link 3</a></div>
<div><a [routerLink]="['/events', 4]" routerLinkActive="active">Link 4</a></div>

navbar.component.ts

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../user/auth.service';
import { ISession } from '../events/shared/event.model';
import { EventService } from '../events/shared/event.service';
import { Router } from '@angular/router'

@Component({
    selector: 'navbar',
    templateUrl: 'app/nav/navbar.component.html',
    styles: [`
    .nav.navbar-nav { font-size: 15px; }
    #searchForm { margin-right: 100px; }
    @media (max-width: 1200px) { #searchForm {display:none}}
    li > a.active { color: #F97924;  }
    `]
})

export class NavBarComponent implements OnInit {
    constructor(private authService: AuthService, private eventService: 
EventService, private router: Router ) { 

    }
    searchTerm: string = '';
    foundSessions: ISession[];
    ngOnInit() { }

    //Other code

    onLinkClick(id: number){
        this.router.navigate(['events/', id]) // THIS LINE FIRES, BUT DOES NOT CAUSE THE COMPONENT TO RELOAD - **ONLY THE URL** CHANGES.
    }
}

routes.ts

import { Routes } from '@angular/router';
import { Error404Component } from './errors/404.errors.component';
import {
    EventsListComponent,
    EventDetailsComponent,
    CreateEventComponent,
    EventRouteActivator,
    EventListResolver,
    CreateSessionComponent
} from './events/index';

export const AppRoutes: Routes = [
    { path: 'events/new', component: CreateEventComponent, canDeactivate: 
['canDeactivateCreateEvent'] },
    { path: 'events', component: EventsListComponent, resolve: { events:         
EventListResolver } },
    { path: 'events/:id', component: EventDetailsComponent, canActivate: 
[EventRouteActivator] } // <======= THIS ONE FAILS TO FIRE THE COMPONENT MORE THAN ONCE!
    { path: 'events/session/new', component: CreateSessionComponent },
    { path: '404', component: Error404Component },
    { path: '', redirectTo: '/events', pathMatch: 'full' },
    { path: 'user', loadChildren: 'app/user/user.module#UserModule' },

]

events-app.component(root component)

import { Component } from '@angular/core'

@Component({
    selector: 'events-app',
    template: `
    <navbar></navbar>
    <router-outlet></router-outlet>
    `
})
export class EventsAppComponent {

} 

app.module.ts

import { NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { NavBarComponent } from './nav/navbar.component'
import {
    JQ_TOKEN,
    TOASTR_TOKEN,
    Toaster,
    CollapsableComponent,
    SimpleModalComponent,
    ModalTriggerDirective
} from './common/index';
import {
    EventsListComponent,
    EventThumbnailComponent,
    EventService,
    EventDetailsComponent,
    CreateEventComponent,
    EventRouteActivator,
    EventListResolver,
    CreateSessionComponent,
    SessionListComponent,
    DurationPipe
} from './events/index'
import { AppRoutes } from './routes';
import { RouterModule } from '@angular/router';
import { Error404Component } from './errors/404.errors.component';
import { EventsAppComponent } from './events-app.component'
import { AuthService } from './user/auth.service'

declare let toastr: Toaster;
declare let jQuery: Object;

@NgModule({
    imports: [
        BrowserModule,
        RouterModule.forRoot(AppRoutes),
        FormsModule,
        ReactiveFormsModule
    ],
    declarations: [
        EventsAppComponent,
        EventsListComponent,
        EventThumbnailComponent,
        NavBarComponent,
        EventDetailsComponent,
        CreateEventComponent,
        Error404Component,
        CreateSessionComponent,
        SessionListComponent,
        CollapsableComponent,
        SimpleModalComponent,
        DurationPipe,
        ModalTriggerDirective
    ],
    providers: [
        EventService, EventRouteActivator, EventListResolver, AuthService,
        { provide: 'canDeactivateCreateEvent', useValue: checkDirtyState },
        { provide: TOASTR_TOKEN, useValue: toastr } ,
        { provide: JQ_TOKEN, useValue: jQuery }

    ],
    bootstrap: [EventsAppComponent]
})
export class AppModule { }

function checkDirtyState(component: CreateEventComponent) {
    if (component.isDirty) {
        return window.confirm('You have not saved this component.  Do you 
really want to cancel?');
    }
    return true;
}

非常感谢任何想法。

1 个答案:

答案 0 :(得分:2)

正如GünterZöchbauer在上面的评论中所说,答案是:

在组件中,通过订阅来监听参数的更改:

ngOnInit() { 
    this.sub = this.route.params.subscribe((params) =>{
        this.event = this.eventService.getEvent(+params['id']);
    });
}

这个“bug”在Pluralsight课程“Angular Fundamentals”中有解释。 非常感谢。