我是Angular2的新手.我有一个JSON对象,如下所示:
var options = { param1: "parama1", param2: "parama2", param3: "parama3" };
应转换为查询字符串并附加到外部URL以重定向页面,如下所示:
ngOnInit(){ window.location.href = someurl?param1=param1¶m2=param2¶m3=param3; }
我正在寻找一种方法将其转换为查询字符串.在JQuery $.param()
和AngularJS $httpParamSerializerJQLike()
中都有这个.我搜索过,但我一无所获.我想知道有没有办法在angular2中做到这一点.
没有字符串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());
顺便说一下,这会自动编码.
此解决方案适用于大多数复杂类型
任何人都想知道如何做到这一点,我写了一个扩展,应该使用c#.Net Core 1.1和Typescript 2.2.2 WebApi看起来像这样.
请记住在您使用它的地方也要包含这两个导入
import { URLSearchParams } from '@angular/http'; import 'rxjs/add/operator/map' export class QueryStringBuilder { static BuildParametersFromSearch(obj: T): URLSearchParams { let params: URLSearchParams = new URLSearchParams(); if (obj == null) { return params; } QueryStringBuilder.PopulateSearchParams(params, '', obj); return params; } private static PopulateArray (params: URLSearchParams, prefix: string, val: Array ) { for (let index in val) { let key = prefix + '[' + index + ']'; let value: any = val[index]; QueryStringBuilder.PopulateSearchParams(params, key, value); } } private static PopulateObject (params: URLSearchParams, prefix: string, val: T) { const objectKeys = Object.keys(val) as Array ; 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 (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()); } } }
这适用于我目前使用的所有复杂类型.