Динамически добавлять маршрут из http api в app-routing.module.ts angular 10

#angular #routes #angular-ui-router #angular-httpclient

#angular #маршруты #angular-ui-router #angular-httpclient

Вопрос:

Я столкнулся с проблемой, и хотя я нашел много возможностей в старой версии angular, она по-прежнему не работает для меня в версии angular 10. Я думаю, что я довольно новичок в angular….

Я пытаюсь создать веб-сайт с клиентским API angular через вызовы https из другого приложения, и я хочу обновить свои маршруты из app-routing.module.ts, добавляя маршруты, которые я получаю.

Но когда я использую функцию resetConfig для обновления моего массива appRoute (пытаясь перейти к маршруту localhost: 4200 / упоминания или localhost: 4200 / биография по примеру), он завершается неудачей, и я получаю со своей консоли этот ответ :

 ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'mentions'
Error: Cannot match any routes. URL Segment: 'mentions'
    at ApplyRedirects.noMatchError (router.js:2316)
    at CatchSubscriber.selector (router.js:2300)
    at CatchSubscriber.error (catchError.js:27)
    at MapSubscriber._error (Subscriber.js:75)
    at MapSubscriber.error (Subscriber.js:55)
    at MapSubscriber._error (Subscriber.js:75)
    at MapSubscriber.error (Subscriber.js:55)
    at MapSubscriber._error (Subscriber.js:75)
    at MapSubscriber.error (Subscriber.js:55)
    at ThrowIfEmptySubscriber._error (Subscriber.js:75)
    at resolvePromise (zone-evergreen.js:798)
    at resolvePromise (zone-evergreen.js:750)
    at zone-evergreen.js:860
    at ZoneDelegate.invokeTask (zone-evergreen.js:399)
    at Object.onInvokeTask (core.js:27418)
    at ZoneDelegate.invokeTask (zone-evergreen.js:398)
    at Zone.runTask (zone-evergreen.js:167)
    at drainMicroTaskQueue (zone-evergreen.js:569)
    at ZoneTask.invokeTask [as invoke] (zone-evergreen.js:484)
    at invokeTask (zone-evergreen.js:1621)
  

вот файл и методы

 //app-routing.module.ts

import {NgModule, OnInit,APP_INITIALIZER} from '@angular/core';
import {Router, RouterModule, Routes} from '@angular/router';
import {CarouselNavigationComponent} from './carousel-navigation/carousel-navigation.component';
import {AppComponent} from './app.component';
import {BookComponent} from './book/book.component';
import {EventComponent} from './event/event.component';
import {EventDetailComponent} from './event/event-detail/event-detail.component';
import {FourOhFourComponent} from './four-oh-four/four-oh-four.component';
import {MaintenanceComponent} from './maintenance/maintenance.component';
import {PageService} from './services/page.service';
import {PageComponent} from './page/page.component';


const appRoute: Routes = [
    {path: '' , component: CarouselNavigationComponent},
    {path: 'fr' , component: AppComponent},
    {path: 'gallery' , component: BookComponent},
    {path: ':lang/gallery' , component: BookComponent},
    {path: ':lang/events' , component: EventComponent},
    {path: ':lang/event/:id' , component: EventDetailComponent},
    {path: ':lang/golden-book' , component: AppComponent},
    {path: ':lang/contact' , component: AppComponent},
    {path: 'test/:id' , component: AppComponent},
    {path: 'fr/:id' , component: AppComponent},
    {path: 'not-found' , component: FourOhFourComponent},
    {path: 'events' , component: EventComponent},
    {path: 'event/:id' , component: EventDetailComponent},
    {path: 'maintenance' , component: MaintenanceComponent}
];


export function configurationInit(pageService: PageService) {
    return (): Promise<any> => {
        return pageService.init();
    };
}



@NgModule({
    declarations: [],
    imports: [
      RouterModule.forRoot(appRoute)
    ],
    exports: [RouterModule],
    providers: [
        PageService,
        {
            provide: APP_INITIALIZER,
            useFactory: configurationInit,
            deps: [PageService],
            multi: true
        }
]
})



export class AppRoutingModule {

    constructor() {}


}
  

//page.service.ts

 import {Injectable, OnInit} from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Observable, Subject, Subscription} from 'rxjs';
import { environment } from '../../environments/environment';
import {Router} from '@angular/router';
import {PageComponent} from '../page/page.component';

const httpOptions = {
    headers: new HttpHeaders({
        'Content-Type':  'application/json; charset=utf-8',
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
        'Access-Control-Allow-Headers': 'X-Requested-With, Content-Type, accept'
    })
};
@Injectable()

export class PageService {
    constructor(private httpClient: HttpClient, private router: Router){}
    pages: any[] = [];


    init() {
         return new Promise<void>((resolve, reject) => {
             const url = environment.apiWeb   '/page';
             const arr = this.router.config;
             this.httpClient.get<any[]>(url, httpOptions)
                 .subscribe((response) => {
/*from the application the callback function I receive these datas
[ {
active: "1"
alias: "mentions"
author: "1"
content: "Lorem ipsum"
date_add: "2020-05-19 19:25:00"
id_lang: "1"
id_page: "1"
id_page_lang: "1"
last_update: "2020-05-19 20:00:00"
title: "Mentions légales"},
{
active: "1"
alias: "biography"
author: "1"
content: "Je suis un poulet. que dire d'autre"
date_add: "2020-05-22 07:00:00"
id_lang: "1"
id_page: "2"
id_page_lang: "2"
last_update: "2020-05-19 00:00:31"
title: "biographie"}]

*/
                         response.forEach(
                              (res) => {
                                  arr.push({
                                      path: res.alias,
                                      component: PageComponent
                                  });
                              }
                          );
                         this.pages = response;
                     },
                     (errors) => {
                         console.log(errors);
                     }
                 );
             console.log(arr);
             this.router.resetConfig(arr);
             resolve();
         });
    }

}
  

Когда я пытаюсь добавить маршрут без http, с простым объектом это работает, но с HttpClient это не удается.

вот данные, которые я получаю, когда я делаю консольный журнал в page.service.ts

ответ на сообщение консоли

Извините за мой плохой английский, если у вас есть идея или проблема, я постараюсь. с наилучшими пожеланиями

Ответ №1:

Я не видел «упоминания» маршрутизатора в списке определения маршрутизатора. Это причина кода ошибки, с которым вы столкнулись. Пожалуйста, проверьте еще раз, чтобы определить класс маршрутизатора

Комментарии:

1. упоминания и биография — это маршрут, который я получаю из своего веб-приложения. я помещаю их в page.service.ts и обновляю свой маршрутизатор с помощью router.resetConfig(arr). В консоли Chrome они находятся в моем новом массиве, но, похоже, они игнорируются, когда я пытаюсь получить доступ к ссылкам, связанным