简体   繁体   中英

routing and breadcrumbs in Angular2

I tried a few breadcrumb approaches and they seem useless out of the box since most of my routes do not include enough information.

for example:

/products
/product:id
/subproudcts:productId
/subproductdetail:subproductId

each of these paths is a deeper dive into the catalog. SubProduct:500 is a child of Product:27 etc.

I would like breadcrumbs to look like this:

My Product A > SubProducts > Sub Product Detail B

by default, above paths do not contain enough information for breadcrumb component to magically figure this out.

One solution i was thinking is making routes longer like this:

/products/detail:id/subproducts
/products/detail:id/subproducts/detail:id

not sure if this is what breadcrumbs components are looking for if it's the "right" way to go.

my question is: what's a good solution to having a nice custom breadcrumb that can 1. show all paths including link to sub lists, and 2. show names of each selected parent.

I would do it via service

import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from "rxjs"

class UrlWithNameAndOtherMeta {
    url: number;
    name: string;
    getUrl() {
        return "<a href=" + this.url + ">" + name + "</a>"
    }
}

class BreadcrumbService {
    breadcrumbEmiter = new BehaviorSubject<UrlWithNameAndOtherMeta[]>([]);
    listOfItems = [];
    push(page: UrlWithNameAndOtherMeta) {
        this.listOfItems.push(page);
        this.breadcrumbEmiter.next(this.listOfItems);
    }
    pop() {
        this.listOfItems.pop();
        this.breadcrumbEmiter.next(this.listOfItems);
     }
    get breadcrumbAsObservable() : Observable<UrlWithNameAndOtherMeta[]>{
        return this.breadcrumbEmiter.asObservable();
    }
}

Then in your breadcrumb component you subscribe for breadcrumbAsObservable . After that from pages you push pop.

PS. But honestly i am not sure if I not reinventing wheel :)

I am a bit late to answer here. Can you please check if xng-breadcrumb handles your use-cases along with few other well-thought use cases

  • Default routing with support for nested routing
  • The declarative approach of defining breadcrumbs in routing config
  • Dynamic asynchronous way to update any route's breadcrumb
  • way to skip specific routes from displaying in breadcrumbs

you can check - https://github.com/udayvunnam/xng-breadcrumb

Demo app showing the breadcrumbs usage - https://xng-breadcrumb.netlify.com

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM