How to convert JSON to query string in angular2?

▼魔方 西西 提交于 2019-12-31 21:56:45

问题


I'm new to Angular2. I have a JSON object, as below:

var options = {
  param1: "parama1",
  param2: "parama2",
  param3: "parama3"
};

which should convert to query string and append to an external URL to redirect the page like below:

ngOnInit(){
     window.location.href = someurl?param1=param1&param2=param2&param3=param3;
}

I'm looking for a way to convert it to query string. In JQuery, $.param() and in AngularJS $httpParamSerializerJQLike() are there for this. I'd searched, but I got nothing. I want to know is there any way to do it in angular2.


回答1:


A more 'official' method without the string concats:

import {URLSearchParams} from '@angular/http'
let options = {
  param1: "param1",
  param2: "param2",
  param3: "param3"
};

let params = new URLSearchParams();
for(let key in options){
    params.set(key, options[key]) 
}

console.log("http://someUrl?" + params.toString());

This does automatic encoding by the way.




回答2:


This solution will work with most complex types

Incase anyone was wondering how to do this, I've written an extension that should work with c# .Net Core 1.1 and Typescript 2.2.2 WebApi which looks like so.

Remember to include these two imports where you are using it as well

import { URLSearchParams } from '@angular/http';
import 'rxjs/add/operator/map'

export class QueryStringBuilder {
    static BuildParametersFromSearch<T>(obj: T): URLSearchParams {
        let params: URLSearchParams = new URLSearchParams();

        if (obj == null)
        {
            return params;
        }

        QueryStringBuilder.PopulateSearchParams(params, '', obj);

        return params;
    }

    private static PopulateArray<T>(params: URLSearchParams, prefix: string, val: Array<T>) {
        for (let index in val) {
            let key = prefix + '[' + index + ']';
            let value: any = val[index];
            QueryStringBuilder.PopulateSearchParams(params, key, value);
        }
    }

    private static PopulateObject<T>(params: URLSearchParams, prefix: string, val: T) {
        const objectKeys = Object.keys(val) as Array<keyof T>;

        if (prefix) {
            prefix = prefix + '.';
        }

        for (let objKey of objectKeys) {

            let value = val[objKey];
            let key = prefix + objKey;

            QueryStringBuilder.PopulateSearchParams(params, key, value);
        }
    }

    private static PopulateSearchParams<T>(params: URLSearchParams, key: string, value: any) {
        if (value instanceof Array) {
            QueryStringBuilder.PopulateArray(params, key, value);
        }
        else if (value instanceof Date) {
            params.set(key, value.toISOString());
        }
        else if (value instanceof Object) {
            QueryStringBuilder.PopulateObject(params, key, value);
        }
        else {
            params.set(key, value.toString());
        }
    }

}

This is working for all the complex types I've used so far.




回答3:


How about this:

ngOnInit(){
    let options = {
      param1: "param1",
      param2: "param2",
      param3: "param3"
    };

    let myQuery = 'http://someurl?'
    for (let entry in options) {
        myQuery += entry + '=' + encodeURIComponent(options[entry]) + '&';
    }

    // remove last '&'
    myQuery = myQuery.substring(0, myQuery.length-1)

    window.location.href = myQuery;
}

myQuery value is ?param1=param1&param2=param2&param3=param3.



来源:https://stackoverflow.com/questions/41761523/how-to-convert-json-to-query-string-in-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!