如何使用 Http 拦截器提交 Angular 表单

How submit Angular form with Http Interceptor

您知道如何使用 HttpInterceptor 提交表单吗?我的 GET 方法可以使用拦截器获取令牌并带来结果等...但是当我尝试提交我的表单时没有任何反应,后端没有被调用。

TokenInterceptor.ts

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

  constructor(private kcService: KeycloakService) {}

  intercept(request: HttpRequest<any>, next: HttpHandler) : Observable<HttpEvent<any>>{
    return from(this.kcService.init())
      .pipe(switchMap(authToken => {
        debugger;
        if(authToken){
          const headers = request.headers
            .set('Authorization', 'Bearer ' + authToken)
            .append('Content-Type', 'application/json');
          console.log(authToken);
          const reqClone = request.clone({
            headers
          });
          return next.handle(reqClone);
        }
      }));
  }

}

ItemService.ts

@Injectable()
export class ItemService {

    itensUrl = 'http://localhost:8080/itens'

    constructor(private http: HttpClient, private kcService: KeycloakService) { }

    list(){
     return this.http.get<any[]>(this.itensUrl);
    }

    addiction(item: any){
      return this.http.post(this.itensUrl, item);
    }
  }

app.modules.ts:

 providers: [
    ItemService,
    KeycloakService,
    {
      provide: HTTP_INTERCEPTORS,
      useClass: TokenInterceptor,
      multi: true
    }

ItemPatrimonyComponent.ts

export class ItemPatrimonyComponent implements OnInit {

  itens = [];

  constructor(private itemService: ItemService) { }

  ngOnInit() {
    this.listAll();
  }

  listAll(){
    this.itemService.list().subscribe(data => this.itens = data)
    console.log(this.itens);
  }

  add(frm:FormControl){
    this.itemService.addiction(frm.value)
      .subscribe(() => {
        frm.reset();
        this.listAll();
       });
  }

问题出在 Keycloak init 函数上,您无法调试问题,因为在拦截器上,您将调试器添加到 init 的回调内部而不是外部。 如果调用 init 并刷新页面(keycloak 的作用)你永远不会看到回调调试器工作,你需要做的是在你的 keycloak 服务上而不是直接调用 init 验证令牌是否已经定义如果它 returns 令牌,而不是在每个请求上调用 keycloak.init。 类似于:

if (this.keycloak.token) {
  return Promise.resolve(this.keycloak.token);
}
return this.keycloak.init().then(()=> this.keycloak.token)