首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular 7-通过url导航到动态路径

Angular 7-通过url导航到动态路径
EN

Stack Overflow用户
提问于 2018-12-03 18:00:18
回答 1查看 4.4K关注 0票数 1

我想添加从我的API返回的新路由。但这些路线并没有按时注册。我对angular很陌生,当我导航到例如/ http://localhost:4200/iphone-7时,它会把我带到第404页,但是当我使用<a [routerLink]="['iphone-7']">this</a>导航到那条路线时,它就可以工作了。如何确保我的angular应用程序按时注册路线?

app-routing.module.ts

代码语言:javascript
复制
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

代码语言:javascript
复制
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标准生成的

附注:这位于routes变量中

EN

回答 1

Stack Overflow用户

发布于 2018-12-04 00:22:20

尝试再添加一个具有相同组件的路由。

使用防护更新路由

代码语言:javascript
复制
{ path: '', component: HomeComponent, pathMatch: 'full' },
{ path: ':id', component: HomeComponent, canActivate: [ProductsGuards] },

添加防护

代码语言:javascript
复制
@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

        }
      })
    );
  }
}

使用以下功能更新您的服务

代码语言:javascript
复制
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');
  }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53591319

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档