【问题标题】:How to add dynamic content type in Angular如何在 Angular 中添加动态内容类型
【发布时间】:2021-05-30 22:51:02
【问题描述】:

我有一个服务来发出 HTTP 请求,如下所示。我正在尝试在服务的请求标头中添加动态内容类型。

如何在apiCall 函数中添加内容类型作为额外参数?

@Injectable()
export class AjaxService {
    constructor(private _http: HttpClient) {}

    apiCall(
        data: any,
        url: string,
        method: 'DELETE' | 'GET' | 'HEAD' | 'POST' | 'JSONP' | 'PUT',
        isRawUrlFormat: boolean = false
    ) {
        if (isRawUrlFormat === false) {
            url = environment.apiUrl + '/' + url;
        }

        let request$: Observable<any>;

        switch (method) {
            case 'GET':
                request$ = this._http.get(url, { observe: 'response' });
                break;
            case 'POST':
                request$ = this._http.post(url, data, { observe: 'response' });
                break;
            case 'PUT':
                request$ = this._http.put(url, data, { observe: 'response' });
                break;
            default:
                request$ = this._http.request(method, url, {
                    observe: 'response'
                });
        }

        return request$.pipe(
            map((apiResult: HttpResponse<any>) => {
                const responseObject = apiResult.body;
                return responseObject;
            })
        );
    }
}

【问题讨论】:

    标签: angular angular-http-interceptors


    【解决方案1】:

    您尝试动态执行 http 请求是否有原因?通常,如果您创建了一个服务,您只需为每个 http 请求创建一个自定义方法,然后导入该服务并在需要时调用 get、post、put、delete 等方法?

    Some Class...    
    export Class AjaxService{
        
        httpGET(params){
            ...some code
        }
        
        httpPOST(params){
            ...some code
        }
        
        httpPUT(params){
            ...some code
        }
        
        httpDELETE(params){
            ...some code
        }
        
        
    }
    
    import AjaxService;
    
    AjaxSerive.httpGET(api_url).subscribe(res => {
        results = res;
    })
    
    AjacSerive.httpPOST(api_url, data).pipe(
        map(res: HttpResponse<any> => {
            results = res;
        })
    }
    

    这些方法是异步的,它们不会返回您的数据,它们会返回 Observables 或 Subscriptions。您需要在要将服务导入到的类中处理它们,以便将数据绑定到指定的变量。

    【讨论】:

      【解决方案2】:

      我已经创建了一个类似的服务,在这里查看我的示例:https://github.com/ferhado/ferhado/blob/master/projects/http/src/lib/http.service.ts

      在 NPM 上 https://www.npmjs.com/package/@ferhado/http

      【讨论】:

        猜你喜欢
        • 2019-02-18
        • 1970-01-01
        • 1970-01-01
        • 2014-05-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-16
        相关资源
        最近更新 更多