import { Routes, RouterModule } from '@angular/router'; import { HTTP_INTERCEPTORS } from '@angular/common/http'; import { MyInterceptor } from './my.interceptor';
const routes: Routes = [ { path: 'home', component: HomeComponent }, { path: 'about', component: AboutComponent }, { path: 'contact', component: ContactComponent } ];
import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
@Injectable()
export class MyInterceptor implements HttpInterceptor {
intercept(req: HttpRequestBearer ${token}
)
});
return next.handle(authReq);
}
return next.handle(req);
}
}
providers: [ { provide: HTTP_INTERCEPTORS, useClass: MyInterceptor, multi: true } ],
RouterModule.forRoot(routes)
在HTTP客户端中,使用以下代码示例来确保正确调用:
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http';
@Injectable() export class ApiService { constructor(private http: HttpClient) {}
getData() { return this.http.get('http://example.com/data'); } }