【问题标题】:intercept FormData from request body in angular以角度从请求正文中截取 FormData
【发布时间】:2021-07-10 06:16:01
【问题描述】:

发送

let formData = new FormData();
http.post - - - - - - - - - - - formData;

得到

request = { body: FormData }

我想做角截距

if(FormData's value instanceof File) {
    pass without intercept
}

我该怎么做?

request = { body : FileFormData(ex: FormData only for File) }

【问题讨论】:

    标签: angular request intercept


    【解决方案1】:

    使用 HttpInterceptor

    import { Injectable } from '@angular/core';
    import {
      HttpEvent, HttpInterceptor, HttpHandler, HttpRequest
    } from '@angular/common/http';
    
    import { Observable } from 'rxjs';
    
    @Injectable()
    export class FormDataInterceptor implements HttpInterceptor {
    
      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // FormData's value instanceof File, something along the lines of
        if(req.body instanceof File) {
            return next.handle(req);
        }
        // Do intended logic here
        return next.handle(req);
      }
    }
    

    然后注册拦截器: app.module.ts

    providers: [
       { provide: HTTP_INTERCEPTORS, useClass: FormDataInterceptor, multi: true }
    ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-02
      • 2020-05-04
      • 1970-01-01
      • 2021-05-11
      • 1970-01-01
      • 2015-06-06
      • 2017-03-31
      • 1970-01-01
      相关资源
      最近更新 更多