假设我有一个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中反映这一点,并更新浏览器历史记录,以便后退按钮将工作?这可能吗?我在这里问了一个类似的问题,但使用路由器代替。我认为这两个选项可以在不同的场景中使用,但我就是不能正确使用它们。
如果你使用this.router.navigate(...)
或<a [routerLink]="..."
导航到相同的路由,只有参数值改变,那么组件实例被重用,浏览器历史记录被更新。