更改网址时不会加载组件

时间:2016-03-30 18:06:32

标签: angular angular2-routing

我试图导航到兄弟组件,网址会发生变化,但组件不会更改,它会保留在当前组件中。我必须刷新应用程序才能加载违反SPA设计的组件。 我测试了来自Navbar组件的相同链接,该组件也是PlatformResult组件的兄弟,它可以正常工作,但在尝试从StatusTable组件导航时不起作用。我确定我在这里做些蠢事,请帮我弄清楚这里发生了什么。

作为此问题的解决方法,我使用事件服务从状态组件通知应用程序组件,应用程序组件导航到URL并按预期加载组件。但我不喜欢这个,因为对于一个简单的问题来说这似乎是一种过度杀伤

app.component.ts

  @Component({
selector: 'app',
template: `
<div class="wrapper">
    <navbar></navbar>
    <div class="content-wrapper container-fluid"> 
       <div class="row">
       <div class="col-md-12">
        <div class="alert alert-danger" role="alert" [ngStyle]="{'display': style}">{{error}}</div>
        <router-outlet></router-outlet>
       </div>
       </div>

    </div>
   <app-footer></app-footer>
</div>
`,
directives: [Navbar, Sidebar, Footer, ROUTER_DIRECTIVES],
providers: [ROUTER_PROVIDERS, DataService, NavigationService],
styleUrls: ['styles/app.css']

   @RouteConfig([{
        path: '/status',
        name: 'Home',
        component: StatusTable,
        useAsDefault: true
    }, {
            path: '/platform',
            name: 'Platform',
            component: PlatformResult
        }, {
            path: '/**',
            name: 'Other',
            redirectTo: ['Home']
        }])

export class AppComponent {
    error: string;
    showError: boolean;
    style: Object;

    constructor(private navigationService: NavigationService, private router: Router) {
        // listen to navigation events
        // AS A WORKAROUND, THIS IS THE WAY I CAN NAVIGATE TO /platform from /status
        navigationService.navigationAnnounced$.subscribe(
            message => {
                router.navigate([message.componentName, message.params]);
            }
        );
    }
}

status.template.html(部分)

...  
<thead class="heading" [ngClass]="{'fade-table': spinner}">
        <tr>
            <th>Diffs ({{diffCount}})</th>
            <th *ngFor="#platform of platforms">
                <div class="vertical" style="width:30px">
                    <a [routerLink]="['/Platform', {name: platform.name}]">
                        <small>{{platform?.name}}<span class="text-danger" *ngIf="platform.ssl">({{platform?.ssl}})</span></small>
                    </a>
                </div>
            </th>
            <th><small>Assigned To</small></th>
            <th><small class="pull-left">Comments</small></th>
        </tr>
        <tr>
        </tr>
    </thead>
    ....

1 个答案:

答案 0 :(得分:2)

中删除ROUTER_PROVIDERS
providers: [ROUTER_PROVIDERS, DataService, NavigationService],

仅将其添加到bootstrap(AppComponent, [ROUTER_PROVIDERS])

拥有全局实例。如果您在组件上添加它们,组件将获得一个打破路由的不同(新)实例。