Angular CanActivate无法正常工作

时间:2018-09-16 16:12:59

标签: angular angular-routing angular-router

我转到内容存在的路径“ / event / 1”,它不转到路径“ / event / 1”,但重定向到路径“ /”。但我转到了不存在的路径“ / event / 8”,它按预期转到了404页。我怎么错?

Angular CanActivate does not work as expected.

这是我的代码。

在routes.ts中,路径“ events /:id”是麻烦制造者。

import { Routes } from "@angular/router";
import { EventListComponent } from "./events/event-list/event-list.component";
import { EventDetailComponent } from "./events/event-detail/event-detail.component";
import { CreateEventComponent } from "./events/create-event/create-event.component";
import {NotFoundComponent} from "./errors/not-found/not-found.component";
import {EventRouteActivator} from "./events/event-detail/event-route-activator.service";

export const appRouters: Routes = [
  { path: "events", component: EventListComponent },
  { path: "events/new", component: CreateEventComponent },
  { path: "events/:id", component: EventDetailComponent, canActivate: [EventRouteActivator] },
  { path: "404", component: NotFoundComponent },
  { path: "", redirectTo: "/events", pathMatch: "full" },
];

在event-route-activator.service

import { Router, ActivatedRouteSnapshot, CanActivate } from "@angular/router";
import { Injectable } from "@angular/core";
import { EventService } from "../services/event.service";

@Injectable()
export class EventRouteActivator implements CanActivate {
  constructor(private eventService: EventService, private router: Router) {}
  canActivate(route: ActivatedRouteSnapshot) {
    const eventExists = !!this.eventService.getEvent(+route.params["id"]);
    if (!eventExists) {
      this.router.navigate(["/404"]);
      return eventExists;
    }
  }
}

在app.modules中,我已经导入了404页面的NotFoundComponent,并导入了EventRouteActivator作为提供程序。

import { ToastrService } from "./events/services/toastr.service";
import { EventDetailComponent } from "./events/event-detail/event-detail.component";
import { appRouters } from "./routes";
import { CreateEventComponent } from "./events/create-event/create-event.component";
import { NotFoundComponent } from "./errors/not-found/not-found.component";
import { EventRouteActivator } from "./events/event-detail/event-route-activator.service";

@NgModule({
  declarations: [
    AppComponent,
    EventListComponent,
    EventThumbnailComponent,
    NavbarComponent,
    EventDetailComponent,
    CreateEventComponent,
    NotFoundComponent
  ],
  providers: [EventService, ToastrService, EventRouteActivator],
  imports: [BrowserModule, RouterModule.forRoot(appRouters)],
  bootstrap: [AppComponent]
})
export class AppModule {}

0 个答案:

没有答案