Angular 7中间件问题咨询:是否有类Laravel中间件?如何路由设站语言?
Hey there! Let's tackle your Angular 7 questions one by one—happy to help out!
Angular 7 doesn’t have a direct "middleware" concept like backend frameworks such as Laravel, but it offers equivalent tools to handle request/route interception and logic checks:
- Route Guards: Control access to routes (e.g., check if a user is logged in before allowing access to a dashboard). Common guard types include
CanActivate,CanDeactivate, andCanLoad. - HTTP Interceptors: Intercept all outgoing HTTP requests and incoming responses. Use cases include adding auth headers, handling global errors, or showing loading spinners for API calls. You create custom interceptors by implementing the
HttpInterceptorinterface. - Resolvers: Fetch data before a route activates, ensuring your component has all necessary data when it loads (avoids messy async logic inside components).
类似Laravel的中间件替代方案
While Angular doesn’t have global middleware exactly like Laravel, you can combine Route Guards and HTTP Interceptors to replicate similar behavior. For example, a CanActivate guard can run global checks (like validating a session) before any route loads, just like a Laravel middleware.
实现带语言前缀的路由(如https://example.com/en/about)
Since you’re already using path-based language routing, here’s a step-by-step implementation tailored to Angular 7:
Step 1: Configure the routing module
Set up routes with a language parameter as the root segment:
// app-routing.module.ts import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { AboutComponent } from './about/about.component'; import { HomeComponent } from './home/home.component'; import { LanguageGuard } from './language.guard'; const routes: Routes = [ // Group all language-prefixed routes { path: ':lang', canActivate: [LanguageGuard], // Add guard to validate language code children: [ { path: '', component: HomeComponent }, { path: 'about', component: AboutComponent }, // Add other routes here ] }, // Redirect root to default language (English) { path: '', redirectTo: '/en', pathMatch: 'full' } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
Step 2: Create a Language Guard
Validate that the language parameter is supported (prevents invalid codes like /fr/about if French isn’t enabled):
// language.guard.ts import { Injectable } from '@angular/core'; import { CanActivate, ActivatedRouteSnapshot, Router } from '@angular/router'; @Injectable({ providedIn: 'root' }) export class LanguageGuard implements CanActivate { private supportedLangs = ['en', 'de']; // List your supported languages constructor(private router: Router) { } canActivate(route: ActivatedRouteSnapshot): boolean { const lang = route.paramMap.get('lang'); if (lang && this.supportedLangs.includes(lang)) { return true; // Valid language, allow access } else { this.router.navigate(['/en']); // Redirect to default language return false; } } }
Step 3: Integrate a Language Service (with @ngx-translate)
Manage the active language and sync it with the route parameter. First, install @ngx-translate/core and @ngx-translate/http-loader (for loading translation files):
npm install @ngx-translate/core@11 @ngx-translate/http-loader@4 --save
Then create the language service:
// language.service.ts import { Injectable } from '@angular/core'; import { TranslateService } from '@ngx-translate/core'; import { ActivatedRoute } from '@angular/router'; @Injectable({ providedIn: 'root' }) export class LanguageService { constructor(private translate: TranslateService, private route: ActivatedRoute) { this.translate.setDefaultLang('en'); // Set default language } setLanguage(lang: string): void { if (['en', 'de'].includes(lang)) { this.translate.use(lang); localStorage.setItem('preferredLang', lang); // Persist user preference } } getCurrentLanguage(): string { return this.translate.currentLang || 'en'; } }
Update your root component to sync the route language with the service:
// home.component.ts import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { LanguageService } from '../language.service'; @Component({ selector: 'app-home', templateUrl: './home.component.html' }) export class HomeComponent implements OnInit { constructor(private route: ActivatedRoute, private langService: LanguageService) { } ngOnInit(): void { const lang = this.route.snapshot.paramMap.get('lang'); if (lang) this.langService.setLanguage(lang); } }
Step 4: Add Language Switcher Links
Let users switch languages while keeping the current route:
<!-- app.component.html --> <nav> <button (click)="switchLanguage('en')">English</button> <button (click)="switchLanguage('de')">Deutsch</button> <a [routerLink]="['/', 'en', 'about']">English About</a> <a [routerLink]="['/', 'de', 'about']">Deutsche About</a> </nav> <router-outlet></router-outlet>
// app.component.ts import { Component } from '@angular/core'; import { Router } from '@angular/router'; import { LanguageService } from './language.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html' }) export class AppComponent { constructor(private router: Router, private langService: LanguageService) { } switchLanguage(lang: string): void { // Update the language segment in the current URL const urlSegments = this.router.url.split('/'); urlSegments[1] = lang; this.router.navigateByUrl(urlSegments.join('/')); this.langService.setLanguage(lang); } }
内容的提问来源于stack exchange,提问作者Abduhafiz

