Angular 5 HttpParams not being set
Asked Answered
U

1

14

I have thins very simple function:

createParams(paramsArray, withToken: boolean): HttpParams {
    let params = new HttpParams();
    let currentUser = JSON.parse(localStorage.getItem('currentUser'));
    params.set('access_token', JSON.stringify(currentUser.token));
    return params;
}

When i debug this the params variable does not contain any keys nor values:

enter image description here

What am i doing wrong?

Unsure answered 23/5, 2018 at 7:2 Comment(0)
M
32

Try this:

let Params = new HttpParams();
Params = Params.append('access_token', JSON.stringify(currentUser.token));

OR

let params = new HttpParams().set('access_token', JSON.stringify(currentUser.token)); 

HttpParams is intended to be immutable. The set and append methods don't modify the existing instance. Instead they return new instances.

Moralize answered 23/5, 2018 at 7:7 Comment(4)
I have no clue who thought this was a good API. Since it's not!Nobleminded
@MelroyvandenBerg As a Software Engineer who has been developing for years, I think It makes sense as it is beneficial for developers in many areas, You need to know how it behaves. Then we all can enjoy it.Moralize
As a software engineer for years, I don't think it's a good OOP practice / interface for HttpParams. After all you assume set does also works on an existing object, why shouldn't it? Saying it's intended to be immutable doesn't give me a good reason why it should be immutable.Nobleminded
@MelroyvandenBerg Being immutable is not a bad idea; Also, Your point of view is not wrong. But we have to consider all probable challenges to implement a new framework and we must balance it, Totally it can be a good decision that doesn't create any confusion. In the end, we all have to ask it from engineers who know all the considerations and have been developing this frameworkMoralize

© 2022 - 2024 — McMap. All rights reserved.