Angular 7 form data序列化

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']);
        });
    }
}

结果:
Angular 7 form data序列化_第1张图片

你可能感兴趣的:(Typescript,Angular)