Angular 7 form data序列化

本文详细介绍了一个基于Angular框架的HTTP服务封装实现,包括如何利用Angular的HttpClient进行POST请求,以及参数序列化的具体方法。通过实例展示了登录服务的创建与组件间的调用,为开发者提供了一种高效、规范的API调用解决方案。
摘要由CSDN通过智能技术生成

common.http.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpParams, HttpHeaders, HttpResponse, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
const httpOptions = {
	headers: new HttpHeaders({ "Content-Type": "application/x-www-form-urlencoded;charset=utf-8" }),
}
@Injectable()
export class HttpUtil {
    public HttpUtil:any;
    constructor(private http: HttpClient) {}
    public post(url:string, data?: any) {
        const params = typeof(data)==='object' && String(data) !== '[object File]'? this.paramFormat(data): data;
        return this.http.post(url,params,httpOptions);
    }
    // 序列化参数
    private paramFormat (data: any): string {
        let paramStr='', name, value, subName, innerObj;
        for (name in data) {
            value = data[name];
            if (value instanceof Array) {
                for (let i of value) {
                    subName = name;
                    innerObj = {};
                    innerObj[subName] = i;
                    paramStr += this.paramFormat(innerObj) + '&';
                }
            } else if (value instanceof Object) {
                Object.keys(value).forEach(function(key){
                    subName = name + '[' + key + ']';
                    innerObj = {};
                    innerObj[subName] = value[key];
                    paramStr += this.paramFormat(innerObj) + '&';
                })
            } else if (value !== undefined && value !== null) {
                paramStr += encodeURIComponent(name) + '='
                    + encodeURIComponent(value) + '&';
            }
        }
        return paramStr.length ? paramStr.substr(0, paramStr.length - 1) : paramStr;
    };
}

service.ts

import { Injectable } from '@angular/core';
import { HttpUtil } from '../../shared/common/common.http';
@Injectable()
export class LoginService {
    constructor(private httpUtil: HttpUtil) { };
    login(data: object) {
        return this.httpUtil.post('xxxx',data);
    }
}

login.component.ts

import { Component } from '@angular/core';
import { LoginService } from './login.service';
@Component({
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.scss'],
    providers: [LoginService]
})
export class LoginComponent {
    params: object = {
        username: '',
        password: '',
    }
    constructor( private loginService: LoginService ) { }
    submit = () :void => {
        this.loginService.login(this.params).subscribe(data => {
           this.router.navigate(['/index']);
        });
    }
}

结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值