1
假设我有一个Component
作为一种主要细节。我希望网址能够反映细节部分的变化,而无需重新加载整个Component
。Angular2更新了属性更改的URL(带有浏览器历史记录)
这是我有:
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,但使用路由器。我认为这两种选择都可以用于不同的场景,但我无法让它们正确。
好的。所以我应该使用像'/ home'或'home?categoryId = 123'这样的路线,而不是在这种情况下呢? – Joel
这样参数就是一个查询参数。你想要的是路由参数。 '/ home/123'会匹配你的路由配置。 –
但是,如何在没有选择类别的情况下覆盖最初的情况?那将是'/ home'。然后选择一个类别为“/ home/12”,这将是另一条路线。两条路线都应加载相同的主/明细视图。 – Joel