例:
// app.module.ts中
import { ToastrModule } from 'ngx-toastr';
import { AuthGuard } from './auth.guard';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
BrowserAnimationsModule,
ToastrModule.forRoot() // 添加toastr模块
],
providers: [
AuthGuard // 添加AuthGuard服务
],
bootstrap: [AppComponent]
})
export class AppModule { }
例:
// sample.component.ts中
import { ToastrService } from 'ngx-toastr';
@Component({
selector: 'app-sample',
templateUrl: './sample.component.html'
})
export class SampleComponent implements OnInit {
constructor(private toastr: ToastrService) { }
ngOnInit(): void {
this.toastr.success('Hello World!'); // 使用toastr服务输出信息
}
}
例:
// auth.guard.ts中
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '@angular/router';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private router: Router) { }
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean {
// 在此处增加用户认证逻辑
if(!isAuthenticated){
this.router.navigate(['/login']); // 重定向到登录页
return false;
}
return true;
}
}