The parameter type 'string | null' cannot be assigned to the argument type 'string'. The type 'null' is not compatible with the type 'string'.ts(2345)

Issue: The parameter type 'string | null' is not compatible with the expected type 'string'. The value 'null' is not a valid string.ts(2345)

Error on Line: this.setSession(res.body._id, res.headers.get('x-access-token'), res.headers.get('x-refresh-token'));


  constructor(private httpClient: HttpClient, private webService: WebRequestService, private router: Router) { }

  login(email: string, password: string) {
    return this.webService.login(email, password).pipe(
      shareReplay(),
      tap((res: HttpResponse<any>) => {
        // authentication tokens are present in the response headers
        this.setSession(res.body._id, res.headers.get('x-access-token'), res.headers.get('x-refresh-token'));
        console.log('Successfully logged in');
        console.log(res);
      })
    )
  }

  logout() {
    this.removeSession();
  }

  private setSession(userId: string, accessToken: string, refreshToken: string) {
    localStorage.setItem('user-id', userId);
    localStorage.setItem('access-token', accessToken);
    localStorage.setItem('refresh-token', refreshToken);
  }

  private removeSession() {
    localStorage.removeItem('user-id');
    localStorage.removeItem('access-token');
    localStorage.removeItem('refresh-token');
  }

Answer №1

It appears that one of the arguments res.body._id,

res.headers.get('x-access-token')
,
res.headers.get('x-refresh-token')
is returning a null value, even though you have defined their types as strings.

-Try using console.log(res.body._id, res.headers.get('x-access-token'), res.headers.get('x-refresh-token')) to determine which one is null.

-Consider changing the declaration of

private setSession(userId: string, accessToken: string, refreshToken: string)
to
private setSession(userId: string|null, accessToken: string|null, refreshToken: string|null)

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

Creating a custom date selection component in Angular 2 RC1

Can anyone recommend a datepicker that is compatible with Angular 2 RC1? I noticed that ng2-datepicker seems to be using angular2 RC1, but when trying to install it, it's asking for Angular 2 Beta. Would appreciate any assistance. Thank you in advan ...

Combining URLs in Angular 6 - A Step-by-Step Guide

How can I concatenate the commonUrl from CommonClass in Angular 6 for category.service.ts? common-class.ts export class CommonClass { constructor(public commonUrl : string = 'http://localhost:3000'){}; } category.service.ts import { CommonC ...

Vue3 with Typescript may either display an error message or remain empty when handling props

I've been attempting to utilize the default Quasar card component in order to display data received from props. Unfortunately, I haven't had any success as my component remains empty and I keep encountering various errors with each attempt. Rece ...

Is it better to convert fields extracted from a JSON string to Date objects or moment.js instances when using Angular and moment.js together?

When working on editing a user profile, the API call returns the following data structure: export class User { username: string; email: string; creationTime: Date; birthDate: Date; } For validating and manipulating the birthDate val ...

The attribute 'pixiOverlay' is not found in the property

Working on my Angular 8 project, I needed to display several markers on a map, so I chose to utilize Leaflet. Since there were potentially thousands of markers involved, I opted for Leaflet.PixiOverlay to ensure smooth performance. After installing and imp ...

What is the best way to incorporate multiple Bootstrap templates into an Angular project without causing conflicts between them?

When incorporating a bootstrap template into the admin interface, it is important to consider that its design may vary from the template used for visitors. Mixing multiple styles based on different templates can lead to conflicting styles and can potenti ...

Angular failing to detect Leaflet TimeDimension

Recently, I integrated leaflet-timedimension into an Angular project that utilizes ngx-leaflet. However, I encountered a hurdle when trying to utilize the geoJson time dimension feature. It appears that Angular is not recognizing the leaflet-timedimension ...

Key Assignment in Vue FireStore - Potential Undefined Object Situation

My goal is to assign Firestore data, passed through props, to a reactive proxy object in Vue. However, I am encountering an error that says: Object is possibly 'undefined'. (property) fireStoreData: Record<string, any> | undefined To strea ...

Tricks for simulating e.preventDefault in Angular

Creating Test Cases for a Method <input type="number" min="10" max="100" (keydown)="checkLength1($event,inputNumber)"#inputNumber/> ts file checkLength1(e: { key: string | number; keyCode: number; preventDef ...

Are there more efficient methods for utilizing local scope when defining a variable?

Having experience in the ML world, I'm used to creating variables with limited scope like this: let myVar = let result1 = doSomething() let result2 = doSomethingElse() result1 + result2 In TypeScript, it seems you can achieve similar sco ...

What is the best way to retrieve all designs from CouchDB?

I have been working on my application using a combination of CouchDB and Angular technologies. To retrieve all documents, I have implemented the following function: getCommsHistory() { let defer = this.$q.defer(); this.localCommsHistoryDB ...

Is it possible for a class method in Typescript to act as a decorator for another method within the same

Can we implement a solution like this? class A { private mySecretNumber = 2; decorate (f: (x :number) => number) { return (x: number) => f(this.mySecretNumber * x); } @(this.decorate) method (x: number) { return x + 1; } } I h ...

Creating a component with the name "c-name" is not possible because the specified module does not exist

Current working directory /src/app Directory of app.module.ts /src/app/app.module.ts Adding a new component to this directory catalog/single/configurator/[new component here] Attempt #1 to add a component ng g c catalog/single/configurator/details-popo ...

Obtain pictures from MongoDB for a website using Angular6

I'm currently in the process of developing my website and I want to showcase an image from my database on the header. Each customer is assigned a unique logo based on their ID, but I'm unsure how to use Angular to display it. Below is my code s ...

Retrieve the property values of `T` using a string key through the `in

Having trouble accessing a property in an object using a string index, where the interface is defined with in keyof. Consider the following code snippet: interface IFilm { name: string; author: string; } type IExtra<T extends {}> = { [i ...

Tips for creating a TypeScript function that can accept an array of concatenated modifiers with the correct data type

Can I modify data using a chain of function modifiers with correct typing in TypeScript? Is this achievable? const addA = (data: {}) => { return { ...data, a: "test" } } const addB = (data: {}) => { return { ...data, ...

Ways to dynamically authenticate in AuthGuard and return a true value

I am working on an auth guard that has multiple conditions, and I am looking for a way to dynamically return a true value. Here is the relevant code snippet: auth.guard.ts canLoad(route: Route, segments: UrlSegment[]): Observable<boolean>|Promise&l ...

Utilizing Express JS to make 2 separate GET requests

I am facing a strange issue with my Express API created using Typescript. The problem revolves around one specific endpoint called Offers. While performing operations like findByStatus and CRUD operations on this endpoint, I encountered unexpected behavior ...

Allow web applications in Apache ServiceMix to communicate across different domains by enabling Cross

My current project involves deploying an angular2 webapp in servicemix as a war file. As a result, the app runs on the localhost:8181/angular2webapp URL. Additionally, I have a bundle installed for handling REST requests, which essentially functions as a c ...

Implement a uniform CSS design across all elements within an Angular 2 application

I am trying to make use of some basic and reusable CSS rules in my Angular application, such as: .ng-invalid { border-left: 5px solid #a94442; } .ng-valid { border-left: 5px solid #42A948; } However, I want these rules to be applied to all compo ...