【发布时间】:2018-12-03 10:00:18
【问题描述】:
我想添加从我的 API 返回的新路由。
但是这些路线没有按时注册。当我导航到例如/ http://localhost:4200/iphone-7 时,我对角度很陌生,这会将我带到 404 页面,但是当我使用 <a [routerLink]="['iphone-7']">this</a> 导航到该路线时,它会起作用。如何确保我的 Angular 应用按时注册路线?
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 标准生成的
【问题讨论】:
-
这能解决问题吗?,我得到了端点,但路由没有注册,这只是一个简单的重构
-
不,它不会解决问题。我删除了我的评论,因为它与问题没有任何关系。对不起
-
想通过不和谐或其他方式帮助我解决此问题,以便我可以向您展示问题吗?
-
对不起,我现在没有时间。除非其他人能帮忙,否则我稍后会看看。
-
谢谢你,我这几天一直在研究这个问题。