带后退按钮的Angular2路由

问题描述 投票:2回答:1

贝娄是结构

app.component
/posts/posts.component
/shared/shared.component
/shared/gallery.component

在app.component下,我有

@RouteConfig([
    { path: './shared/...', name: 'Shared', component: SharedComponent },
    { path: './posts/...', name: 'Posts', component: PostsComponent}
])

在posts.component下,我有

@RouteConfig([
{ path: '/', name: 'PostList', component: PostListComponent, useAsDefault: true },
{ path: '/:id', name: 'PostDetail', component: PostDetailComponent },
{ path: '/:id/gallery', name: 'Gallery', component: GalleryComponent }

])

在gallery.component下,我有

import {Component, Input} from 'angular2/core';
import {Router} from 'angular2/router';

import {Photo} from './photo';
import {GalleryService} from './gallery.service';

@Component({
    selector: 'my-gallery',
    template: `
<my-photo *ngFor="#item of items" [style.backgroundImage]="'url(' + item.thumb + ')'"></my-photo>
    `
})

export class GalleryComponent {
    @Input() items;

    constructor(private _galleryService: GalleryService) {
        if (this._galleryService.get()) {
            this.items = this._galleryService.get(); 
        }
    }
}

问题是,我可以导航到画廊(从http://server/posts/123http://server/posts/123/gallery)好吧,但是当我点击浏览器后退按钮时,即使网址更改回来,视口中没有任何内容发生变化,我的画廊也不会被移除和我的帖子没有加载。

如果我切换到HashLocationStrategy,后退按钮可以工作,但我宁愿不改变它。

routing angular back-button
1个回答
0
投票

您还没有提到您正在使用的浏览器,但这是Safari上的一个典型问题,它会加载页面的持久/缓存版本,但不会像其他浏览器一样实例化javascript。

我不能代表新的rc1路由器,因为我还没有测试它,但你可以使用旧的router-deprecated版本在主应用程序组件中使用以下内容来解决这个问题。这更像是一种解决方案,并不打算长期使用,因为这个问题肯定会在ng2接近其正确版本时修复。

constructor(_router:Router, 
            _applicationRef: ApplicationRef) {
    _router.subscribe((uri)=> {
        if (Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
            // We appear to be using Safari...
            _applicationRef.zone.run(() => _applicationRef.tick());
        }
    });
}

这段代码的问题在于它会触发每个状态变化,这意味着我们可能会强迫浏览器执行更多操作,但正如我所说,将其视为短期修复。

© www.soinside.com 2019 - 2024. All rights reserved.