属性更改时Angular2更新URL(包含浏览器历史记录)

时间:2016-10-04 15:54:33

标签: angular angular2-routing angular2-components

假设我有Component作为一种主要细节。我希望网址反映详细信息部分的更改,而不重新加载整个Component

这就是我所拥有的:

home.routing.ts

import { ModuleWithProviders } from "@angular/core";
import { Routes, RouterModule } from "@angular/router";

import { HomeComponent } from "./home.component";
import { ItemListComponent } from "./item-list.component";

const homeRoutes: Routes = [
    {
        path: "home",
        component: HomeComponent,
        children: [
            {
                path: ":categoryId",
                component: HomeComponent
            }
        ]
    },
    {
        path: "home",
        component: HomeComponent
    }
];

export const homeRouting: ModuleWithProviders = RouterModule.forChild(homeRoutes);

home.component.ts

import { Component, OnInit } from "@angular/core";
import { Router, ActivatedRoute, Params } from "@angular/router";

...

@Component({
    template: `
            <div *ngFor="let category of categories">
                <span (click)="onSelect(category)">{{category.title}}</span>
            </div>
            <item-list></item-list>
    `,
})
export class HomeComponent implements OnInit {
    categories: Category[];
    selectedCategoryId: string;

    constructor(
        private route: ActivatedRoute,
        private router: Router) {
    }

    ngOnInit() {
        this.getCategories();

        // Update selectedCategoryId if it is set in the URL
        this.route.params.forEach((params: Params) => {
            this.selectedCategoryId = params["categoryId"];
        })
    }

    onSelect(category: Category) {
        this.selectedCategoryId = category.id;

        // This will trigger a change in the item-list component and the
        // items will be loaded based on the selected category. 
        // What can I do here to reflect the change of selected category
        // in the URL?
    }

    getCategories() {
        ...
        this.categories = categoriesFromRestAPI;
    }
}

项-list.component.ts

import { Component, Input } from "@angular/core";

...

@Component({
    selector: "item-list",
    template: `
        <div *ngIf="categoryId">
            <div *ngFor="let item of items">
                <span>{{item.text}}</span>
            </div>
        </div>
    `
})
export class ItemListComponent {
    private _categoryId: string;
    items: Item[];

    constructor() {
    }

    @Input()
    set categoryId(categoryId: string) {
        this._categoryId = categoryId;
    }

    get categoryId() {
        return this._categoryId;
    }

    getItems() {
        // Get items based on this._categoryId;
        items = itemsFromRestApi;
    }
}

当用户选择某个类别时,如何在URL中反映该类别,并更新浏览器历史记录以使后退按钮有效?可能吗?我问了一个类似的问题here,但是使用了路由器。我认为这两个选项都可以在不同的场景中使用,但我无法让它们正确。

1 个答案:

答案 0 :(得分:5)

如果使用this.router.navigate(...)<a [routerLink]="..."导航到同一路线,其中只有参数值发生变化,则会重复使用组件实例并更新浏览器历史记录。