تايب سكريبت - كيفية سرد/عرض جميع المسارات في @Routes في تطبيق Angular2 الخاص بي


لدي سؤال سريع. أنا حالياً أتصفح https://angular.io/docs/ts/latest/api/router/Router-class.html ولكن كنت أتساءل، في main.ts الخاص بي في Angular2 لدي المسارات معرفة على النحو التالي:

@Routes([
    { path: '/', component: HomeComponent },
    { path: '/about-me', component: AboutMeComponent },
    { path: '/food', component: FoodComponent },
    { path: '/photos', component: PhotosComponent },
    { path: '/technology', component: TechnologyComponent },
    { path: '/blog', component:Blogomponent },
])

الآن في مكون آخر أقوم باستيراد فئة Router. في المكون الخاص بي (أو قالب المكون) أرغب في التكرار عبر جميع المسارات المعرفة لدي أو مجرد القدرة على الوصول إليها. هل هناك طريقة مدمجة للقيام بذلك؟ مثل وظيفة ما تعيد مصفوفة من الكائنات؟ إليكم فكرة بدائية عما أريد...

@Component({
    selector: 'ms-navigation',
    templateUrl: 'src/navigation/navigation.template.html',
    directives: [ ROUTER_DIRECTIVES ]
})

export class NavigationComponent {
    constructor(private router:Router) {   
        // what can I do here to get an array of all my routes?
        console.log(router.routes); ????
    }
}

الإجابة رقم 1

تحديث يوليو 2024: بما أن هذا الجواب كان منذ وقت طويل، لم أتمكن من متابعة جميع الإصدارات الأحدث، هناك ملحق لهذا الجواب من قبل أدرين للإصدارات الأحدث مع التحميل الكسول. يرجى الرجوع إليه أيضًا للإصدارات الأحدث من Angular.


إليك نسخة أفضل ستقوم بسرد كل المسارات الممكنة (تمت إصلاحها حسب التعليقات):

import { Router, Route } from "@angular/router";

constructor(private router: Router) { }

ngOnInit() {
  this.printpath('', this.router.config);
}

printpath(parent: string, config: Route[]) {
  for (let i = 0; i < config.length; i++) {
    const route = config[i];
    console.log(parent + '/' + route.path);
    if (route.children) {
      const currentPath = route.path ? `${parent}/${route.path}` : parent;
      this.printpath(currentPath, route.children);
    }
  }
}

الإجابة رقم 2

من الواضح أن هناك طريقة مضغوطة جدًا للقيام بذلك:

constructor(private router: Router) {}

ngOnInit() {
  console.log('configured routes: ', this.router.config);
}

الإجابة رقم 3

إذا كنت بحاجة فقط إلى مسارات الطرق كسلاسل نصية، يمكنك العثور عليها من خلال التكرار على مصفوفة config الخاصة بكائن Router.

    for (var i = 0; i < this.router.config.length; i++) {
        var routePath:string = this.router.config[i].path;
        console.log(routePath);
    }

الإجابة رقم 4

أنا أستخدم هذا المكوّن للحصول على جميع المسارات في Angular 9

import { Compiler, Component, Injector, OnInit } from '@angular/core';
import { Route, Router } from '@angular/router';

@Component({
  templateUrl: './sitemap.component.html'
})
export class SiteMapComponent implements OnInit {

  public urls: string[] = [];
  constructor(private _router: Router, private compiler: Compiler, private injector: Injector) {

  }

  ngOnInit() {
    this._router.config.forEach(i => {
      this.getPaths(i);
    })
  }

  getPaths(route: Route, parent: string = '') {
    if (route.redirectTo) {
      return;
    }
    if (route.children) {
      route.children.forEach(i => {
        this.getPaths(i, parent + route.path);
      });
    }
    else if (route.loadChildren) {
      (<any>this._router).configLoader.load(this.injector, route).subscribe(i => {
        i.routes.forEach(j => {
          this.getPaths(j, parent + route.path)
        });
      });
    }
    else if (route.path != null) {
      this.setPath(route.path, parent);
    }
  }
  setPath(path, parent) {
    let fullPath: string;
    if (path != null) {
      if (parent) {
        fullPath = `/${parent}/${path}`;
      }
      else {
        fullPath = `/${path}`
      }
    }
    this.urls.push(fullPath)
  }
}

تحديث Angular 14: configLoader.load

(<any>this._router).configLoader.loadChildren

تحديث Angular 17: configLoader.loadChildren

(<any>this._router).navigationTransitions.configLoader.loadChildren