Angular 7 - перейти к динамическому маршруту через URL - PullRequest
0 голосов
/ 03 декабря 2018

Я хочу добавить новые маршруты, которые возвращаются из моего API.Но маршруты не регистрируются вовремя.Я совсем новичок в работе с angular, когда я перехожу к, например, / http://localhost:4200/iphone-7, это приведет меня на страницу 404, но когда я перейду к этому маршруту, используя <a [routerLink]="['iphone-7']">this</a>, это сработает.Как я могу убедиться, что мое угловое приложение вовремя регистрирует маршруты?

app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule, Router } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { ReparationMainComponent } from './reparation-main/reparation-main.component';
import { BrandSelectionComponent } from './reparations/brand-selection/brand-selection.component';
import { ModelSelectionComponent } from './reparations/model-selection/model-selection.component';
import { RepairSelectionComponent } from './reparations/repair-selection/repair-selection.component';
import { PriceSelectionComponent } from './reparations/price-selection/price-selection.component';
import { ConfirmSelectionComponent } from './reparations/confirm-selection/confirm-selection.component';
import { NotFoundComponent } from './not-found/not-found.component';
import { RestfulService } from './helpers/restful/restful.service'



var routesMain: Routes = [
  { path: "", component: HomeComponent },
  { path: "reparatie", component: ReparationMainComponent },
  { path: "reparatie/:device/merk", component: BrandSelectionComponent },
  { path: "reparatie/:device/:brand/model", component: ModelSelectionComponent },
  { path: "reparatie/:device/:brand/:model/soort", component: RepairSelectionComponent },
  { path: "reparatie/:device/:brand/:model/:repair/pakket", component: PriceSelectionComponent },
  { path: "reparatie/:device/:brand/:model/:repair/:package/bevestig", component: ConfirmSelectionComponent },
  { path: '404', component: NotFoundComponent },
  { path: '**', redirectTo: '/404' }
];

@NgModule({
  imports: [RouterModule.forRoot(routesMain)],
  exports: [RouterModule]
})
export class AppRoutingModule {
  constructor(
    private restfullService: RestfulService,
    private router: Router
  ) {
    var routes: Routes = [];
    restfullService.GetWithoutToken("pagina/all").subscribe((observer: Object[]) => {
      observer.forEach(element => {
        let title: string = element["titel"];
        title = title.trim().replace(/ /g, "-").toLowerCase();
        let newRoute = { path: title, component: HomeComponent };
        routes.unshift(newRoute);
      });
      this.router.resetConfig([...routes, ...this.router.config]);
    })

  }
}

Restfull.service.ts => выполняет вызовы моего api

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class RestfulService {

  constructor(private httpClient: HttpClient) { }

  private API_URL: string = "http://localhost:5353/api/";

  GetWithoutToken(endpoint) {
    return this.httpClient.get(`${this.API_URL}${endpoint}`);
  }
}

У меня нет никаких дальнейших изменений в моем приложении, оно было стандартно сгенерировано с помощью ng new

ps Это внутри переменной маршрутов Routes

1 Ответ

0 голосов
/ 03 декабря 2018

Попробуйте добавить еще один маршрут с тем же компонентом.

Обновить маршрут с защитой

{ path: '', component: HomeComponent, pathMatch: 'full' },
{ path: ':id', component: HomeComponent, canActivate: [ProductsGuards] },

Добавить охрану

@Injectable()
export class ProductsGuards implements CanActivate {
  constructor(private restfulService: RestfulService) {}

  canActivate(route: ActivatedRouteSnapshot): Observable<boolean> {
    return this.restfulService.findProduct(route.params.id).pipe(
      map(isFound => {
        if (isFound) {
          return true;
        } else {
          // router.navigate('')
          // Navigate to 404.
          // Make sure that dont use /404 otherwise it will go in cycle
          // or change product route to some other route.
          // like http://localhost:4200/iphone-xs-max-reparatie
          // to http://localhost:4200/products/iphone-xs-max-reparatie

        }
      })
    );
  }
}

обновить службу с помощью следующих функций

findProduct(productFromUrl: string) {
    return this.getProducts().pipe(
      map((products: Product[]) => {
        return products.filter(
          product =>
            product.seoTextTitel
              .toLowerCase()
              .split(' ')
              .join('-') === productFromUrl
        );
      }),
      take(1),
      map(product => !!product)
    );
  }

  getProducts() {
    return this.httpClient.get('http://ros.azurewebsites.net/api/pagina/all');
  }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...