Storing information retrieved from the API for use in different modules

Trying to extract data from a WEB API service using Angular 8 has been quite challenging for me.

A service I created makes the API call:

return this.http.get<UserSession>(uri)
  .pipe(map((json: UserSession) => this.EntryFormAdapter(json)));

This service then utilizes a data adapter to convert the JSON, although I'm unsure if it's necessary due to strong typing. Interestingly, adding properties to the UserSession constructor causes it to malfunction.

UserSession (fully functional):

export class UserSession {
  public SessionId: string;
  public SessionTimeout: number;
  public User: User;
}

UserSession (not functioning correctly):

export class UserSession {
  constructor (public SessionId: string,
      public SessionTimeout: number,
      public User: User) { }
}

I need to keep the UserSession in global data so that the SessionId is accessible for my HMAC HttpInterceptor.

Interceptor (partially implemented):

constructor(private userSession: Observable<UserSession>) {
    this.userSession.subscribe(us => this.sessionId = us.SessionId);
}

I've dedicated countless hours trying to resolve these two key issues: 1) Making a parameterized constructor function properly 2) Storing a global UserSession object for use in other modules.

Answer №1

To successfully configure the app in app.module.ts, I needed to include UserSession in the provider array:

    @NgModule({
  declarations: [
    AppComponent,
    NavMenuComponent,
    HomeComponent,
    CounterComponent,
    FetchDataComponent,
    AddIssueComponent
  ],
    imports: [
    ReactiveFormsModule,
    BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
    HttpClientModule,
    FormsModule,
    RouterModule.forRoot([
      { path: '', component: HomeComponent, pathMatch: 'full' },
      { path: 'counter', component: CounterComponent },
      { path: 'fetch-data', component: FetchDataComponent },
      { path: 'add-issue', component: AddIssueComponent },
    ])
    ],
    providers: [ApiService, UserSession, AppSettings, AppSettingsService,
        //{ provide: APP_INITIALIZER, useFactory: getSettings, deps: [AppSettingsService, ApiService, AppSettings], multi: true },
        { provide: HTTP_INTERCEPTORS, useClass: HmacInterceptorComponent, multi: true }],
  bootstrap: [AppComponent]
})
export class AppModule { }

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 are some effective strategies for creating customizable and dynamic filtering and sorting features in Angular (^11) that can be reused across different components?

I am looking to integrate custom ordering and filtering capabilities into my application in a way that is easily reusable across various components. These functions will be essential for enabling users to sort list/table contents and filter arrays within t ...

Ways to determine if a specified character sequence is present in an Enumerator?

One of my coding dilemmas involves an enum that looks like this: export enum someEnum { None = <any>'', value1 = <any>'value1', value2 = <any>'value2', value3 = <any>'value3' ...

Unexpected INTERNAL error encountered with Firebase's Cloud Function update

Currently, I am immersed in a project involving Vue.js 3, Typescript, and Firebase. However, while attempting to integrate new cloud functions, I came across an unexpected issue: Failed to load resource: the server responded with a status of 500 () Un ...

What happens when two style() functions are passed into the query() function for Angular Animations?

As someone who is relatively new to angular animations, I have reviewed the angular.io animation documentation multiple times in order to grasp how everything functions. While I believe I have a decent understanding, there are certain scenarios that the do ...

Is it possible to access BreakpointObserver in Angular Material before the page has finished loading?

When utilizing the Angular BreakpointObserver in combination with Angular Material, I encounter an issue where the observer only triggers a change after it detects a difference. This becomes problematic on initial page load as there is no existing change t ...

Incorporating the id attribute into the FormControl element or its parent in Angular 7

I'm attempting to assign an id attribute to the first invalid form control upon form submission using Angular reactive forms. Here is my current component code: onSubmit() { if (this.form.invalid) { this.scrollToError(); } else { ...

The failure to import a node module in next.js with typescript

I'm currently working on integrating a package called bcrypt into my project. I have successfully installed it using npm install bcrypt. Although the package is visible in the node_modules folder, I am encountering an error when trying to import it i ...

Error TS2304: Unable to locate identifier 'QRScanner'

I am currently exploring https://www.npmjs.com/package/cordova-plugin-qrscanner in order to implement a QR scanning feature in my mobile application. As part of the initial steps, I have written the following code snippet in my typescript file: function o ...

Incorrect Angular Routing Component OpeningI am experiencing an issue where

I am facing an issue with lazy loading a module, where it is not correctly displaying the desired component. Even though the route seems correct, it shows a different component instead. Despite specifying the path for "Push-Campaign", it displays the "Cli ...

Determining interface value based on the presence of another optional interface value

I am working with an interface that looks like this: export interface IButton { label: string; withIcon?: boolean; underlined?: boolean; selected?: boolean; iconName?: string; isLink?: boolean; href?: string; onCLick?: () => void; } My question ...

Transitioning create-react-app from JavaScript to Typescript

A few months ago, I began a React project using create-react-app and now I am interested in transitioning the project from JavaScript to TypeScript. I discovered that there is an option to create a React app with TypeScript by using the flag: --scripts-v ...

Troubleshooting: Resolving the Error "Cannot find Property htmlFor on Custom React Component"

I am currently working with a custom component that looks like this: import React from "react"; import classnames from 'classnames'; import { ButtonVariantColor } from '../types/button'; export type IconButtonProps = { e ...

Creating a wrapper component to enhance an existing component in Vue - A step-by-step guide

Currently, I am utilizing quasar in one of my projects. The dialog component I am using is becoming redundant in multiple instances, so I am planning to create a dialog wrapper component named my-dialog. my-dialog.vue <template> <q-dialog v-bin ...

Angular: Automatically close the side navigation menu when a user clicks anywhere outside of it in the screen

My current issue involves using a sidenav library where I need to close the sidenav when the user clicks anywhere on the screen. Despite several attempts, I have been unable to make it work successfully. Below is the code snippet in question: html < ...

Implementing the breadcrumb component within dynamically loaded modules loaded through the router-outlet component

I'm currently working on an angular 8 breadcrumb component for my application. The requirement is to display it in the content of the page, not just in the header, and it should never be located outside the router-outlet. This has posed a challenge fo ...

The node command line does not recognize the term 'require'

My Typescript project was compiling and running smoothly until recently when I started encountering the error ReferenceError: require is not defined every time I try to run node. I am uncertain whether this issue stems from Typescript, as even when I ru ...

Understanding the process of reading cookies on the Angular2 side that have been set by the C# server

I'm struggling to understand how the angular code can access the cookie that was set on the server side. I found the following code snippet on GitHub. This C# function sets the cookie in the Response object with the last line of code. My question is, ...

Transferring information using TypeScript

My issue arises when transferring data from HTML in the following format Karbohidrat :{{karbohidrat}} <button ion-button (click)="cekHalamanMakanan('karbohidrat')">View carbohydrate foods</button> <br> Then, I retrieve the kar ...

How can I showcase an SVG icon received in base64 format using an img tag?

Having trouble displaying SVG/base64 encoded images through the img tag. Here is the issue at hand: Receiving iconData (as a string) from the server. Attempting to display it in my component. No issues with step 1. Encountering a broken image sign with s ...

"Troubleshooting issues with data loading using React's useEffect function

While working on my project, I encountered a strange issue where the isLoading state is being set to false before the data fetching process is completed. I am using the useEffect hook to show a loading spinner while fetching data from an API, and then disp ...