Http params in Angular 4.3

前端 未结 2 855
星月不相逢
星月不相逢 2020-12-29 11:07

I\'m trying to use the new http client that came out with Angular 4.3. I\'ve checked the docs and the use the HttpParams class but it seems not to be working or

2条回答
  •  一整个雨季
    2020-12-29 12:09

    HttpParams is immutable.

    set() creates and returns a new HttpParams instance, without mutating the instance on which set() is called.

    So the code should be

    const params = new HttpParams().set('personId', personId);
    

    Here is one further thing I struggled with when using this new HttpParams, sometimes we have n number of params to pass, at that time it is useful to have some function that converts parameter object(that we were using before Angular 4.3) to the HttpParams.

    I suggest making toHttpParams function in your commonly used service. So you can call the function to convert the object to the HttpParams.

    /**
     * Convert Object to HttpParams
     * @param {Object} obj
     * @returns {HttpParams}
     */
    toHttpParams(obj: Object): HttpParams {
        return Object.getOwnPropertyNames(obj)
            .reduce((p, key) => p.set(key, obj[key]), new HttpParams());
    }
    

    Update:

    Since 5.0.0-beta.6 (2017-09-03) they added new feature (accept object map for HttpClient headers & params)

    Going forward the object can be passed directly instead of HttpParams.

    This is the other reason if you have used one common function like toHttpParams mentioned above, you can easily remove it or do changes if required.

提交回复
热议问题