我的AuthInterceptor.intercept方法未被调用.把所有必要的代码放在下面.我的代码流:来自login.Component的FormSubmit()方法调用来自login.service()的GenerateToken()方法,后者向服务器发出一个HTTP.POST请求.问题:Inerceptor不会在任何http方法之前执行.谢谢

App.config.ts

import { ApplicationConfig, importProvidersFrom } from '@angular/core';
import { provideRouter } from '@angular/router';

import { routes } from './app.routes';
import { provideAnimations } from '@angular/platform-browser/animations';
import { HttpClient, HttpClientModule, provideHttpClient, withInterceptors, withInterceptorsFromDi } from '@angular/common/http';

export const appConfig: ApplicationConfig = {
  providers: [provideRouter(routes), provideAnimations(),provideHttpClient(withInterceptorsFromDi()),]
};

Login.component.ts

import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule} from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import {MatSnackBar, MatSnackBarModule} from '@angular/material/snack-bar';
import { MatCardModule } from '@angular/material/card';
import { LoginService } from '../../services/login.service';
import { UserService } from '../../services/user.service';
import { TempService } from '../../services/temp.service';


@Component({
  selector: 'app-login',
  standalone: true,
  imports: [MatInputModule, MatFormFieldModule, MatButtonModule, FormsModule,MatSnackBarModule,MatCardModule],
  providers:[MatSnackBar,LoginService,UserService,TempService],
  templateUrl: './login.component.html',
  styleUrl: './login.component.css'
})
export class LoginComponent {

  loginData={
    username:"",
    password:""
  };

  constructor(private snack:MatSnackBar, private login:LoginService,private temp:TempService){}

  formSubmit(){
    console.log('login button clicked '+this.loginData.username+', '+this.loginData.password);
    if(this.loginData.username.trim() == '' || this.loginData.username == null){
      this.snack.open("Username cannot be null!","ok",{
        duration:3000,
      });
      return;
    }

    if(this.loginData.password.trim() == '' || this.loginData.password == null){
      this.snack.open("Password field cannot be null!","ok",{
        duration:3000,
      });
      return;
    }

    // request server to generate token
    this.login.generateToken(this.loginData)
    .subscribe({
      next:(data:any)=>{
        console.log('success');
        console.log(data);

        //token has been successfully created
        this.login.loginUser(data.token);
        this.login.getCurrentUser().subscribe({
          next:(user:any)=>{
            this.login.setUser(user);
            console.log(user);
            //redirect... ADMIN : admin dashboard
            //redirect... NORMAL : normal dashboard
          }
        })
      },
      error:(error:any)=>{
        console.log("Error "+ error);
      }
    });

  }
}

Login.service.ts


import { Injectable, NgModule } from '@angular/core';
import baseUrl from './helper';
import { HttpBackend, HttpClient } from '@angular/common/http';
import { authInterceptorProviders } from './auth.interceptor';



@NgModule({
  providers: [authInterceptorProviders],
})

@Injectable({
  providedIn: 'root'
})
export class LoginService {
  // private http: HttpClient;
  // constructor(httpBackend:HttpBackend) {
  //   this.http = new HttpClient(httpBackend);
  //  }
  constructor(private http:HttpClient) {

  }

  //get current user
  public getCurrentUser(){
    return this.http.get(`${baseUrl}/current-user`);
  }

  //generate token

  public generateToken(loginData: any) {
    console.log("genrate Token start");
    return this.http.post(`${baseUrl}/generate-token`, loginData);

  }

  //login user: set token in local storage
  public loginUser(token: string) {
    localStorage.setItem("token_exam_portal", token);
    return true;
  }

  //isLogin: whether user is logged in or not
  public isLoggedIn() {
    let tokenStr = localStorage.getItem("token_exam_portal");
    if (tokenStr == undefined || tokenStr == '' || tokenStr == null) {
      return false;
    }
    return true;
  }

  //logout: remove token_exam_portal from the local storage
  public logout() {
    localStorage.removeItem("token_exam_portal");
    localStorage.removeItem("user");
    return true;
  }

  //get token
  public getToken() {
    return localStorage.getItem("token_exam_portal");
  }

  //set user deatails
  public setUser(user: any) {
    localStorage.setItem('user', JSON.stringify(user));
  }

  //get user
  public getUser() {
    let userStr = localStorage.getItem("user");
    if (userStr != null) {
      return JSON.parse(userStr);
    }
    else {
      this.logout();
      return null;
    }
  }
  // get user role
  public getUserRole(){
    let user = this.getUser();
    return user.authorities[0].authority;// returns only first role
  }
}

Auth.interceptor.ts

import { HTTP_INTERCEPTORS, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from "@angular/common/http";
import { Component, Injectable, NgModule } from "@angular/core";
import { Observable } from "rxjs";
import { LoginService } from "./login.service";

const TOKEN_HEADER = 'Authorization';

@NgModule({
    providers: [LoginService],
})

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

    constructor(private login: LoginService) { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        //add the jwt token
        console.log("Executing intercept method");
        
        let authReq = req;
        const token = this.login.getToken();
        if (token != null) {
            //if token exists then add the token as header to the http request
            authReq = authReq.clone({ setHeaders: { Authorization: `Bearer ${token}` } });
        }
        return next.handle(authReq);
    }
}

export const authInterceptorProviders = (
    {
        provide:HTTP_INTERCEPTORS,
        useClass:AuthInterceptor,
        multi: true,
    }
);

我是新的Angular ,我无法解决这个基本问题.我在互联网上找遍了,但找不到任何合适的解决方案.请给我建议.谢谢.

推荐答案

在独立工作空间中,建议使用功能拦截器,它可以使用withInterceptors()函数提供.

手:

export const appConfig: ApplicationConfig = {
  providers: [
    provideHttpClient(withInterceptors([authInterceptor]))
  ],
};

拦截器:

export function authInterceptor(
  req: HttpRequest<unknown>,
  next: HttpHandlerFn): Observable<HttpEvent<unknown>> {

  // ...interceptor login
  return next(req);
}

有关更多信息,请参阅official interceptors guide.

Angular相关问答推荐

将Angular Metal的芯片组件集成到我的表单中时出错

tabindex on button on button in MatMenu in angular不工作

添加@ nx/webpack插件 destruct 了Nativescript构建

如何使用解析器处理Angular 路由中存储的查询参数以避免任何额外的导航?

FromEvent不工作,本机事件绑定

一次重定向后,所有子路由都处于活动状态

对REST后端的Angular/Priming过滤器请求导致无限循环

如何让 ag-Grid 事件读取私有方法?

Chart.js 如何编辑标题标签 colored颜色

如何在Cypress 测试中切换 Angular 选项卡

如何将新的 FormGroup 或 FormControl 添加到表单

如何在 bootstrap Angular 2 应用程序时调用休息 api

实现自定义 NgbDateParserFormatter 来更改 NgbInputDatepicker 上输入值的格式是否正确?

如何组合两个可观察到的结果?

*ngIf 带有多个异步管道变量

实现autocomplete功能

Angular7 中的 CORS 策略已阻止源http://localhost:4200

如何使用 Angular 6 工作的 ngModel 创建自定义输入组件?

交替行 colored颜色 angular material表

有条件地将 RouterLink 或其他属性指令添加到 Angular 2 中的元素