Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/google-sheets/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 为什么HttpParams不';在角4.3中,t在多行中工作_Angular - Fatal编程技术网

Angular 为什么HttpParams不';在角4.3中,t在多行中工作

Angular 为什么HttpParams不';在角4.3中,t在多行中工作,angular,Angular,从Angular 4.3开始,他们引入了HttpClient而不是Http。 在HttpClient中,我不能使用URLSearchParams作为url查询参数。我使用的不是URLSearchParams,而是httparams 这项工作 var params = new HttpParams().append('a', '1').append('b', '2'); 但为什么这不起作用呢 var params = new HttpParams(); params.append('a', '

从Angular 4.3开始,他们引入了HttpClient而不是Http。 在
HttpClient
中,我不能使用
URLSearchParams
作为url查询参数。我使用的不是
URLSearchParams
,而是
httparams

这项工作

 var params = new HttpParams().append('a', '1').append('b', '2');
但为什么这不起作用呢

var params = new HttpParams();
params.append('a', '1');
params.append('b', '2');

新的HTTP客户端使用不可变的请求对象及其所有组成部分,如
HttpParams
HttpHeaders
。理解为什么要看或读这篇文章

这就是为什么
append
方法在每次调用
append
时合并参数并返回合并的
HttpParams
对象的新实例的原因:

  /**
   * Construct a new body with an appended value for the given parameter name.
   */
  append(param: string, value: string): HttpParams { 
        return this.clone({param, value, op: 'a'}); 
  }

  private clone(update: Update): HttpParams {
    const clone = new HttpParams({encoder: this.encoder}); <-------
    clone.cloneFrom = this.cloneFrom || this;
    clone.updates = (this.updates || []).concat([update]);
    return clone;                                          <--------
  }
append
with
b
参数更新
append
with
a
参数返回的对象

而这种做法,

var params = new HttpParams();
params.append('a', '1');
params.append('b', '2');
append
始终更新
HttpParams
的初始状态,所有中间
append
操作都被有效忽略

因此,您必须使用以前的返回值:

var params = new HttpParams();
params = params.append('a', '1');
params = params.append('b', '2');
或者将快捷方式与
fromObject
一起使用:

let searchParams = new HttpParams({
    fromObject: {
        query: query,
        sort: sort,
        order: order
    }
});

const modified = req.clone({params: searchParams});
或者直接对请求使用
setParams
方法:

const modified = req.clone({setParams: {'query': query, 'sort': sort, 'order': order}});
此外,由于5.1.x,您可以直接传递object,而不是HttpParams的实例:

const params = {
  'a': '1',
  'b': '2'
};

this.http.get('...', { params })
为了让它起作用

var params = new HttpParams();
params.append('a', '1');
params.append('b', '2');
这必须改为

var params = new HttpParams();
params = params.append('a', '1');
params = params.append('b', '2');

它可以动态循环和添加

实际上@Maximus对
HttpParams
对象的不变性做了一个很好的解释,您只需将
参数
替换为循环内的克隆即可

假设您有零到多个可用的
参数
,存储在类似以下结构的数组中:

"params": [
  {
    "key": "p1",
    "value": "v1"
  },
  {
    "key": "p2",
    "value": "v2"
  }
]
根据上述信息,以下帮助函数应该会有所帮助:

export const getHttpParams = (params: Array<any>): HttpParams => {
  let res = new HttpParams();

  for (const item of params)
    res = res.append(item.key, item.value);

  return res;
};

希望有帮助

5.0.0-beta.6(2017-09-03)新功能()可用以来

现在我们可以直接传递对象,而不是
HttpParams

const参数={
“a”:“1”,
“b”:“2”
};
this.http.get('…',{params})
或者代替
HttpHeaders

http.get(“/url”{ 标题:{'My-Header':'Header value'} })
我在这篇文章中尝试了所有其他方法,但收效甚微。因此,我将params链接到一个
HttpParams
singleton上,并调用
toString()
返回一个
string
类型。然后我可以将它传递给http.get(),在构建url参数时,一切似乎都很正常。这是我的
ng-v

$ ng -v
    _                      _                 ____ _     ___
   / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
  / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
 / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
/_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
           |___/
@angular/cli: 1.4.2
node: 8.5.0
os: linux x64
@angular/animations: 4.4.3
@angular/cdk: 2.0.0-beta.10
@angular/common: 4.4.3
@angular/compiler: 4.4.3
@angular/core: 4.4.3
@angular/forms: 4.4.3
@angular/http: 4.4.3
@angular/material: 2.0.0-beta.10
@angular/platform-browser: 4.4.3
@angular/platform-browser-dynamic: 4.4.3
@angular/router: 4.4.3
@angular/cli: 1.4.2
@angular/compiler-cli: 4.4.3
@angular/language-service: 4.4.3
typescript: 2.3.4
下面是一个对我来说效果很好的例子:

// Simplified for example (I'm using Redux and won't go into all that)
private downloadState = { requestType: 'Auction', fileType: 'CSV' };

getStuffFromApi(): Observable<any> {
    const { requestType, fileType } = this.downloadState;
    const apiRoot = 'http://www.example.com';

    const params: string = new HttpParams()
        .set('RequestType', requestType)
        .set('FileType', fileType)
        .set('AuctionType', auctionType)
        .set('BackorderDay', backorderDay)
        .toString();

    return this.http.get(apiRoot, { params })
        .map(res => res.json())
        .catch(err => Observable.of(err.json()));

}
//例如,Simplified(我正在使用Redux,不打算详细说明)
私有下载状态={requestType:'Auction',fileType:'CSV'};
getStuffFromApi():可观察{
const{requestType,fileType}=this.downloadState;
常数apiRoothttp://www.example.com';
const-params:string=new-HttpParams()
.set('RequestType',RequestType)
.set('FileType',FileType)
.set('AuctionType',AuctionType)
.set('BackorderDay',BackorderDay)
.toString();
返回this.http.get(apiRoot,{params})
.map(res=>res.json())
.catch(err=>Observable.of(err.json());
}

谢谢。如果我不知道如何修改我的
参数
。假设我有
c
,那么如果我必须重建
params
我认为这不是一个好方法,那么如何修改
params
对象呢?对不起,我不明白。你能换个说法吗?@imran我想你可以用params.set(“key”,1)。set(“key”,2);这样,键将保留2。params=params.set('a','1')的情况也是如此;正如我刚刚发现的(5)@SoEzPz,是的,在新的HttpClient模块中,大多数实体是不可变的。这是唯一一个对Angular 5有效的解决方案。非常感谢,Pratap A.K说,这是我唯一有效的解决方案。我不得不添加重复的参数,比如{category:1,category:3},这太违反直觉了。。但它是有效的。。非常感谢。
$ ng -v
    _                      _                 ____ _     ___
   / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
  / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
 / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
/_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
           |___/
@angular/cli: 1.4.2
node: 8.5.0
os: linux x64
@angular/animations: 4.4.3
@angular/cdk: 2.0.0-beta.10
@angular/common: 4.4.3
@angular/compiler: 4.4.3
@angular/core: 4.4.3
@angular/forms: 4.4.3
@angular/http: 4.4.3
@angular/material: 2.0.0-beta.10
@angular/platform-browser: 4.4.3
@angular/platform-browser-dynamic: 4.4.3
@angular/router: 4.4.3
@angular/cli: 1.4.2
@angular/compiler-cli: 4.4.3
@angular/language-service: 4.4.3
typescript: 2.3.4
// Simplified for example (I'm using Redux and won't go into all that)
private downloadState = { requestType: 'Auction', fileType: 'CSV' };

getStuffFromApi(): Observable<any> {
    const { requestType, fileType } = this.downloadState;
    const apiRoot = 'http://www.example.com';

    const params: string = new HttpParams()
        .set('RequestType', requestType)
        .set('FileType', fileType)
        .set('AuctionType', auctionType)
        .set('BackorderDay', backorderDay)
        .toString();

    return this.http.get(apiRoot, { params })
        .map(res => res.json())
        .catch(err => Observable.of(err.json()));

}