Angular 2 GET 参数保持为空

标签 angular typescript

您好,我想在 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/

相关文章:

html - 如何设置 Angular 2+ 下拉默认值? [现有问题没有回答我的问题]

Angular 2 http 没有捕获连接被拒绝的错误

angular - 如何在 tsconfig 中包含 Angular(不是 JS)类型,这样我就不必导入它们了?

typescript - Function 接口(interface)是否缺少 new() 签名?

javascript - setTimeout() 函数的 TypeScript 装饰器

angular - ngx-bootstrap timepicker时区偏移导致SQL保存时间错误

typescript - TypeError : self. parent.parent.parent.context 不是函数 Angular 2

javascript - 从响应中获取数组而不是对象

javascript - 使用 defaultExtension 为 systemjs 配置 Angular2 库

typescript - 错误 TS2306 : '...index.d.ts' is not a module