Angular - The type 'ISiteInfo | null' cannot be assigned to the parameter type 'ISiteInfo | undefined'

Within my Angular-12 project, I have defined the following model interface:

export interface ISiteInfo {
  id: number;
  name: string;
  email: string;
}

In addition to this interface, I have a service as well:

import {ISiteInfo} from '../models/site-info.model';

export class SiteInfoService {

  private infoSiteSource = new BehaviorSubject < ISiteInfo | null > (null);
  infoSite = this.infoSiteSource.asObservable();

  setInfoSite(data: ISiteInfo) {
    this.infoSiteSource.next(data);
  }

  constructor(
    private http: HttpClient,
    private api: ApiService,
  ) {}

  public get(refresh: boolean = false): Observable < ISiteInfo > {
    return new Observable(observer => {
      if (!refresh && this.infoSiteSource.getValue()) {
        observer.next(this.infoSiteSource.getValue());
        return observer.complete();
      }
      this.http.get < ISiteInfo > (this.api.baseURL + '/GInfoSite').subscribe(value => {
        this.setInfoSite(value);
        observer.next(this.infoSiteSource.getValue());
        observer.complete();
      });
    });
  }
}

A runtime error has occurred with the message:

Argument of type 'ISiteInfo | null' is not assignable to parameter of type 'ISiteInfo | undefined'. Type 'null' is not assignable to type 'ISiteInfo | undefined'.ts(2345)

The problematic line highlighted in the code is:

this.infoSiteSource.getValue()

This results in an error when 'null' is removed from:

private infoSiteSource = new BehaviorSubject(null);

The error message then changes to:

Argument of type 'null' is not assignable to parameter of type 'ISiteInfo'.ts(2345)

If you have any insights on resolving this issue, your help would be greatly appreciated.

Thank you

Answer №1

Have you considered trying the following approach instead?

const infoSiteSource = new BehaviorSubject < ISiteInfo | undefined > (undefined);

Additionally, it appears that your get method has support for a refresh option. A common way to implement a refresh feature is by using another Observable like this:

// Implementing a refresh feature
private refresh = new BehaviorSubject<boolean>(true);

products$ = this.refresh
  .pipe(
    mergeMap(() => this.http.get<Product[]>(this.productsUrl)
      .pipe(
        tap(data => console.log('Products', JSON.stringify(data))),
        catchError(this.handleError)
      )
    ));

(And to any future editors - hopefully this suggestion proves helpful without the need for editing out unnecessary remarks!)

Answer №2

confidential infoSiteSource = new Subject < ISiteDetails | any> (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

What is the best way to retrieve the chosen item within a Tabmenu component in Primeng?

I have created a simple array of MenuItem objects to populate the Tabmenu component from Primeng. Here is an example: .ts file: items = MenuItem[]; activeItem = MenuItem; //constructor, etc... ngOnInit() { this.items = [ {label: &a ...

Having trouble with the Ng multiselect dropdown displaying empty options?

I'm currently facing a challenge in adding a multiselect dropdown feature to my project. Below is the code I have been working on: HTML <ng-multiselect-dropdown [settings]="searchSettings" [data]="dummyList" multiple> </n ...

Adjusting table to include hashed passwords for migration

How can I convert a string password into a hash during migration? I've tried using the following code, but it seems the transaction completes after the selection: const users = await queryRunner.query('SELECT * FROM app_user;'); user ...

Obtain a Service instance using the console

Back in the days of Angular 1, accessing the injector through the console was a convenient way to retrieve any service: angular.element(document.querySelector('html')).injector().get('MyService') This feature proved to be very helpful ...

Connecting conversations in react

When working with jQuery, I often utilize the modal dialog chaining technique. For example: $.Deferred().resolve().promise() .then(function () { return runDialog1(someProps); // return promise }) .then(function (runDialog1Result) ...

Erase Typescript Service

To remove a PostOffice from the array based on its ID, you can use a checkbox to select the desired element and then utilize its ID for the delete function. Here is an example: let postOffices = [ {postOfficeID: 15, postCode: '3006&ap ...

Creating tests in JestJs for React components that utilize Context Provider and Hooks

As a newcomer to front-end development, I am currently working on authentication with Okta-React. To pass logged-in user information across multiple components, I'm utilizing React context with hooks. While this approach works well, I encountered an i ...

Warning 2531: Potential null value found in object

While working on my Android app in Ionic Angular with Firebase, I encountered a problem in Visual Studio Code yesterday. Despite thorough searching, I couldn't find a solution. Here is the issue This is the TypeScript code from my user registration ...

The Excel Match function is experiencing issues when used in conjunction with the MS-Graph API

Recently, I've encountered an issue with sending a match-function post request to an Excel workbook using the MS-Graph API. Instead of receiving the value of the first column that contains the lookup value, I'm getting the value from the second c ...

Angular lifecycle event

When using the Firebase JS SDK in an Angular project and implementing lifecycle hooks, such as afterViewInit, I noticed that the console message repeats infinitely. How can I ensure that the message only appears once in the console? Thank you for any help ...

Combining and grouping objects by their IDs in a JavaScript array

Information: [ { "id": "ewq123", "name": "Joshua", "order": "Pizza" }, { "id": "ewq123", "name": "Joshua", "order": ...

Using a class as an interface in TypeScript is a common practice when a constructor is

Consider a scenario where I have a class structured like this: class MyClass { a: string } Now, let's say I create a variable with the following definition: let obj: MyClass = { a: 2 } An error will be triggered in Typescript because 2 is not ...

Encountering "token_not_provided" error message on all GET routes in Laravel 5.3 with JWT authentication

I'm currently working on implementing authentication using Laravel 5.3 and Angular 2 with JWT. The authentication part is functioning properly, and I am able to successfully obtain the token. However, when attempting to navigate to any GET routes, an ...

"In TypeScript, when something is undefined, it means its value

I am currently working on a class with code to help manage a database. export class DatabaseHelper { public browserID : number; private ConfigID = 17; } Within this class, I am attempting to access the value of ConfigID SetBrowserID() { ...

Asynchronous execution of Angular 2 services

Currently, I am working on a project that utilizes Angular and RxJS. My approach involves creating an injectable class responsible for fetching data from a JSON source as shown below: import {Injectable, Inject} from '@angular/core'; import {Ht ...

Efficiently Parsing FormData in React with TypeScript for Improved Data Formatting

Recently, I've started working with React and Typescript and one of the challenges I'm facing is managing an editable table with default values that can be updated and submitted. The data format for the parameters is crucial as the fields and va ...

Ways to conduct testing on React Native Typescript app COMPONENTS using jest

I've been struggling to set up testing for my React Native Typescript Components using Jest. Despite searching through various examples and solutions (such as this one, that one, another link, etc.), I still can't seem to get it working. Even fol ...

Creating PDF files from HTML documents using Angular 7

I've been attempting to convert an HTML table into a PDF document without much luck. Even after using jsPDF for the conversion, the quality of the result is not up to par and I'm struggling to figure out why. As I have a tablet at my disposal, ...

Combining the output of two Observables through the CombineLatest method to generate a

I possess two separate collections of information: Data Model: taxControlReference [ { "providerId": "HE", "taxTables": { "STAT": [ 1 ] } }, ...

Exploring the capabilities of utilizing Typescript decorators alongside the Parse SDK JS

In my Typescript project, I am utilizing the Parse SDK JS and have crafted a model class named Person that extends Parse.Object. This class is designed to store data on the server: import * as Parse from 'parse/node' class Person extends Parse. ...