【发布时间】:2016-10-04 15:54:33
【问题描述】:
假设我有一个Component,它充当一种主要细节。我希望 URL 反映详细信息部分的更改,而无需重新加载整个 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;
}
}
item-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,但改用路由器。我认为这两个选项都可以在不同的场景中使用,但我就是无法正确使用它们。
【问题讨论】:
标签: angular angular2-routing angular2-components