utilizing the setter function called "set()" within HttpParams

I am looking to migrate the below method to Angular 7. The issue I am facing is that the data is not being set to the params. Can someone help me figure out why it's not working? It's showing an error message:

Error TS2300: Duplicate identifier 'params'.

updateParamsWithAuth(paramsToSet: HttpParams, appKey: string, fieldToUpdate: string) {
let authToken;
if (appKey && appKey.length > 0) {
  authToken = this.getAccessTokenFromSession();

} else {
  authToken = this.getRSTokenFromSession();
  if (fieldToUpdate === this.FIELD_ACCESS_TOKEN) {
    fieldToUpdate = this.FIELD_RS_TOKEN;
  }
}

// paramsToSet.set(fieldToUpdate, authToken);
let params = new HttpParams().set(fieldToUpdate, authToken);

return params;
}

Answer №1

When calling the updateParamsWithAuth function, you are passing params as a parameter and then declaring it again inside the function. To simplify, you can do the following:

params = new HttpParams().set(field, token);

Alternatively, you can declare it with a different identifier like this:

let httpParams = new HttpParams().set(field, token);

Answer №2

When working with parameters in your method, it's important to avoid redeclaring variables that have already been defined.

To fix this issue, simply update the code from

let params = new HttpParams().set(field, token);
to
params = new HttpParams().set(field, token);

However, consider why you need to redefine it here. If you're initializing it again in the method, there may be no need to pass it as a parameter.

Since you already have params within the method, there is likely no reason to initialize it again.

If you do not require the parameter value for params and are creating a new HttpParams object inside the method, consider removing that parameter or utilizing the existing params instead.

In my opinion, the revised code should look like this:

updateParamsWithAuth(params: HttpParams, appKey: string, field: string) {
    let token;
    if (appKey && appKey.length > 0) {
      token = this.getAccessTokenFromSession();
    } else {
      token = this.getRSTokenFromSession();
      if (field === this.FIELD_ACCESS_TOKEN) {
        field = this.FIELD_RS_TOKEN;
      }
    }

    params = params.set(field, token);

    return params;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging @Inputs with Angular 2's <router-outlet> component for optimal functionality

I am working on a webpage with a sub-navigation feature that displays subviews below a main view. I am looking for a way to pass an object to the subviews using the <router-outlet> so that I only need to retrieve the data once in the main component a ...

A handy tool for easily previewing JavaScript code based on my TypeScript within Visual Studio

Recently I decided to dive into TypeScript. I am eager to find extensions for VisualStudio or Re# that can display live JavaScript based on the TypeScript code I write. Any suggestions for tools like this? Currently, I am using VS 2015 with Re#. ...

Encountering TypeScript error TS2345 while attempting to reject a Promise with an error

I recently encountered a perplexing TypeScript error message that I am struggling to comprehend. The specific error reads as follows: error TS2345: Argument of type '(error: Error) => void | Promise' is not assignable to parameter of type & ...

The TypeScript optional callback parameter is not compatible with the anonymous function being passed to it

Encountering an issue with TS callbacks and function signatures. Here is my scenario: ... //inside a class //function should accept a callback function as parameter refreshConnection(callback?: Function) { //do something //then ca ...

Error: monaco has not been declared

My goal is to integrate the Microsoft Monaco editor with Angular 2. The approach I am taking involves checking for the presence of monaco before initializing it and creating an editor using monaco.editor.create(). However, despite loading the editor.main.j ...

What are some techniques for streamlining this code with Typescript?

I am currently working with the following code snippet: let doNavigate = this.currentScreen === removedFqn; if (doNavigate) { location.reload(); } Does anyone have any suggestions on how I can simplify this code using Typescript? ...

The installation process was unsuccessful due to an error in the postinstall script for [email protected]

While attempting to run npm install, an error message is displayed: Failed at the <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e38d8c8786ce90829090a3d7cdd6cdd3">[email protected]</a> postinstall script. I hav ...

Syntax error: The term 'yield' is restricted

In my current project, I am utilizing typescript along with gulp for compilation tasks. Below is the gulp task that I have set up for compiling my typescript code: gulp.task('compile', function () { return gulp.src('src/**/**/*.*' ...

"Displaying Line Breaks in Text Boxes with Textarea Store Feature

In my Angular 2 application, I am utilizing a textarea element: <textarea [(ngModel)]="value"></textarea> When the value is sent to the server via a REST API, line breaks are not displayed when trying to show the value in the application: {{ ...

Tips for incorporating parameters from the component.ts into @angular/animations

Here is an example of how you can incorporate Angular animations with parameters directly from the HTML file: **Animations.ts** trigger('slowXMove', [ state('posX1State', style({ left: '{{posX1}}px' }), {params: {posX1: ...

Dependency Injection: The constructor of the injectable class is called multiple times

There are multiple classes that inject the TermsExchangeService: import {TermsExchangeService} from './terms-exchange.service'; @injectable() export class TermsExchangeComponent { constructor( private termsExchangeService: TermsExchan ...

Switching an application from Angular 5 to Angular 8 can lead to unexpected styling problems

My current project is based on Angular version 5.2, but we recently decided to upgrade it to Angular 8 along with updating the Angular CLI. After completing the necessary code refactoring for Angular 8, the application builds successfully without any error ...

Using Angular Material to create a data table with a fixed footer and paginator feature

I am facing a challenge with displaying the sum of rows data in the footer section of an Angular Material Table that has fixed footer and header, as well as a paginator. How can I calculate the sum of rows data to show in the footer? https://i.sstatic.net/ ...

modify style when not valid and is touched

When I try to modify the style of an i tag based on the touched and invalid state of another field, only the input tag's style changes and not the i tag. Here's the CSS code I'm using: input.ng-touched.ng-invalid { border-color: red; } ...

Encapsulating a BehaviorSubject within Angular Components for Output

Within my component, I am utilizing a RxJS BehaviorSubject to maintain an internal state (specifically the size of a particular DOM element). My objective is to make this state accessible as an @Output() property. One straightforward implementation that ...

What could be the reason for the malfunctioning of the selection in Angular Material?

HTML code: <ng-container matColumnDef="seleccione"> <mat-header-cell *matHeaderCellDef>Seleccione</mat-header-cell> <!--<mat-header-cell *matHeaderCellDef> <mat-checkbox (change)="$event ? masterToggle() : null" [checked]="s ...

Guide on retrieving the AWS IAM user in string/json format using STS GetCallerIdentity Caller JS/TS

I am attempting to retrieve the AWS IAM Arn user using the STS GetCallerIdentity API provided by Amazon. The following code successfully logs the correct data in the console. Nevertheless, I am encountering difficulty returning the data as a string or JSON ...

"Obtaining subnet identification using the name or CIDR: A step-by-step

I am seeking help on retrieving the subnet id based on subnet name or cidr in order to deploy a nat gateway. Can someone provide guidance on how to obtain the subnet id? Alternatively, does anyone have any best practices for utilizing typescript function ...

Employing async/await for efficient data retrieval

Attempting to utilize async-await in TypeScript Vue 3 to retrieve data, but encountering an issue where the function is already logging 'undefined' (or executing before the function call) private async exportDataOrder() { await this.getDataEx ...

What could be the reason for the absence of Mock Service Worker in a React project that has Typescript enabled?

After attempting to integrate Mock Service Worker into my React project with Typescript support, I encountered errors when running the npm install msw --save-dev command. The terminal displayed the following messages: PS F:\Programming\React Prac ...