我已按照以下方式定义了我的路由:
import { Routes } from '@angular/router';
import { domainGuard } from './guard-routes.service';
import { NotFoundComponent } from './notFound/not-found.component';
export const routes: Routes = [
{
path: '',
loadComponent: () =>
import('./home/home.component').then((m) => m.HomeComponent),
},
{
path: 'users',
loadComponent: () =>
import('./user/user.component').then((m) => m.UserComponent),
},
{
path: 'profile',
loadComponent: () =>
import('./profile/profile.component').then((m) => m.ProfileComponent),
},
{ path: '**', component: NotFoundComponent },
].map((page: any) => {
page.canActivate = [domainGuard];
return page;
});
同时,我的app.component.ts
和app.config
如下所示:
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router';
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule, RouterOutlet, RouterLink, RouterLinkActive],
templateUrl: './app.component.html',
styleUrl: './app.component.scss',
})
export class AppComponent {
title = 'my-app';
}
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [provideRouter(routes)],
};
我在路由中使用了一个函数式守卫,代码如下:
import { Router } from '@angular/router';
import { AuthService } from './auth.service';
import { inject } from '@angular/core';
export const domainGuard = () => {
const router = inject(Router);
const service = inject(AuthService);
if (service.IsAuth()) {
router.navigate(['/user']);
return true;
} else {
router.navigate(['/profile']);
return false;
}
};
以及我的authService
:
import { Injectable } from '@angular/core';
@Injectable()
export class AuthService {
isLoggedIn = false;
login() {
return new Promise((resolve, reject) => {
setTimeout(() => {
this.isLoggedIn = true;
}, 3000);
});
}
logOut() {
return new Promise((resolve, reject) => {
setTimeout(() => {
this.isLoggedIn = false;
}, 3000);
});
}
IsAuth() {
return this.isLoggedIn;
}
}
最后,当我将路由守卫添加到路由时,出现了以下错误:
main.ts:5 ERROR NullInjectorError: NullInjectorError: No provider for _AuthService!.
如何解决这个问题?