您好,我想在 GET 请求中发送参数,但我的搜索参数仍然为空,这是我的代码:
private jwt2() {
let currentUser = JSON.parse(localStorage.getItem('currentUser'));
console.log('current.token ' + currentUser.token);
let params: URLSearchParams = new URLSearchParams(); //PARAMS
params.set('pageSize', '6'); //pageSize
let headers = new Headers({ 'Authorization': currentUser });
console.log("params: " + params); //here I can see correct params
return new RequestOptions({ headers: headers, search: params });
// }
}
我可以在 chrome 中看到正确的 header ,但不能看到搜索参数:
search
URLSearchParams
paramsMap
Map(0)
size(0)
__proto__
Map
[[Entries]]
Array(0)
length(0)
如果我不设置参数并像这样手动将参数写入搜索选项:
return new RequestOptions({ headers: headers, search: 'pageSize=6' });
它有效
最佳答案
我遇到了同样的问题,因为我没有导入 URLSearchParams。
import { URLSearchParams } from '@angular/http';
在没有显式导入 URLSearchParams 的情况下,编译正常,但参数请求为空。
另请注意 RequestOptions 属性 search 已弃用,您应该使用 params :
RequestOptions({ headers: headers, params : myParams })
代替
RequestOptions({ headers: headers, search : params })
使用 params.toString() 的解决方案是一个很好的解决方法,因为 RequestOptionsArgs 也可以是字符串或 URLSearchParams :
export interface RequestOptionsArgs {
url?: string | null;
method?: string | RequestMethod | null;
/** @deprecated from 4.0.0. Use params instead. */
search?: string | URLSearchParams | {
[key: string]: any | any[];
} | null;
params?: string | URLSearchParams | {
[key: string]: any | any[];
} | null;
headers?: Headers | null;
body?: any;
withCredentials?: boolean | null;
responseType?: ResponseContentType | null;
}
它通过传递一个字符串来避免这个问题。在这种情况下,没有必要使用 URLSearchParams。
关于Angular 2 GET 参数保持为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43209693/