Tips for sending user IDs through an Angular 8 interceptor

Alright,

In my Angular application that is using version 8, I have an HttpMaintenanceInterceptor configured without the use of cookies. Instead, I have a getAccessToken method within the authService as shown below:

  getAccessToken(): string {
    return this._user ? this._user.access_token : null;
  }

Additionally, I have a get method defined like this:

getDossierEntry(type: String = '' ): Observable<DossierEntry[]> {
  const entryType = type === '' ? 'all' : 'type/' + type;
  return this.http.get<DossierEntry[]>('/api/patient/${patientUUID}/DossierEntry/' + entryType);
}

The issue arises with the property:

patientUUID

which always turns out to be null. The output looks something like this:

http://localhost:4200/api/patient/$%7BpatientUUID%7D/DossierEntry/type/physical"

To address this problem, I attempted to pass the patientUUID in the HttpMaintenanceInterceptor.

Here's a glimpse at how the HttpMaintenanceInterceptor is structured:


export class HttpMaintenanceInterceptor implements HttpInterceptor {
  needsAuthenticatedUser = true;
  route: string;

  constructor(private auth: AuthService) {}

  // Remaining code for interceptor implementation...

Despite being able to retrieve the accessToken successfully using console.log(accessToken);, unfortunately, I am unable to access the patientUUID. This raises the question - How can I efficiently pass the patientUUID so that it no longer remains null in the API requests?

Thank you!

Upon making modifications:

getDossierEntry(type: String = '' ): Observable<DossierEntry[]> {
  const entryType = type === '' ? 'all' : 'type/' + type;
  return this.http.get<DossierEntry[]>(`/api/patient/{patientUUID}/DossierEntry/` + entryType);
}

However, changing this alone did not resolve the issue at hand. It seems like the root cause lies elsewhere:

console.log('hello there nice to see you!!');

Strangely enough, the execution never reaches this line of code. What could be causing this unexpected behavior?

Answer №1

Using backquotes instead of single quotes is recommended

'/api/patient/${patientUUID}/DossierEntry/'

It is preferable to use:

`/api/patient/${patientUUID}/DossierEntry/`

The same applies when using parsedRoute.replace

const user$ = this.auth.loginStatus()
      .pipe( take( 1 ) );    
       user$.pipe(
         map( user => {
          console.log('hello there nice to see you!!');
          let parsedRoute = this.route;
          if ( this.needsAuthenticatedUser ) {
            if ( !user ) {
              throw Error( 'Tried to call api that requires login without a user profile present' );
            } else {
              parsedRoute = parsedRoute.replace('{userId}', user.profile.sub);
           //   console.log('User Sub ' + user.profile.sub);
              console.log('User participant ' + user.profile.participant);

              parsedRoute = parsedRoute.replace('{patientUUID}', user.profile.participant);
            }
          }
          return environment.ApiOrigin + parsedRoute;
        } ),
      );

This portion of the code will not run as intended since you are not subscribing to the observable. Consequently, the output of console.log will not be displayed on the console

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

Having issues with my Angular 4 + MVC web application not functioning properly in Internet Explorer

After creating an application using Angular 4 and MVC, I noticed a problem specifically with Internet Explorer. The application runs smoothly on Chrome, Firefox, and other browsers except for IE. Does anyone have any suggestions on how to resolve this br ...

How to toggle a checkbox in Angular 5

My terms of service modal is using ngBootstrap and I want the action that closes the modal to be determined by whether the checkbox is checked or not. Here is the HTML code: <ng-template #content let-c="close" let-d="dismiss"> <div class="modal ...

Suggestions for importing by Typescript/VS Code

Imagine you have a file called a.ts that contains 4 named imports: export const one = 1 export const two = 2 export const three = 3 export const four = 4 Next, you have a file named b.ts and you want to import some variables from a.ts. import {} from &a ...

Execute a component method once another component has finished loading completely

My setup involves two components that are both being loaded into my <app-root> element as shown below: <app-header [calendarReference]="calendarRef"></app-header> <app-calendar #calendarRef></app-calendar> This is happening ...

The issue of declaration merging and complications with nested node_modules

Here is the structure I am working with: @my/app node_modules @types/angular @types/angular-translate @my/library node_modules @types/angular The issue arises from the fact that @types/angular-translate extends the definitions of @types/angular ...

Angular 2: Issue with view not reflecting changes in array

I am working on a component that involves two arrays: arrayA and arrayB. The elements in arrayB are filtered from arrayA. In the template, I have: <div *ngFor="let elem of arrayB">{{elem.something}}</div> There is also a button: <button ( ...

Hold off on utilizing information from a single observable until a later time

In my Angular component, I am working with the following code: @Component({...}) export class ComponentOne implements OnDestroy, OnChanges { readonly myBehaviourSub = new BehaviorSubject<Observable<MY_CUSTOM_INTERFACE>>(NEVER); constructo ...

What steps can I take to perform unit testing on a custom element?

While working on a project where I have a class that extends HTMLElement, I came across some interesting information in this discussion: https://github.com/Microsoft/TypeScript/issues/574#issuecomment-231683089 I discovered that I was unable to create an ...

The powerful combination of harp.gl and Angular NG

We've integrated harp.gl into our ng Angular application, but we're encountering issues when trying to connect to data sources that previously worked in our yarn demo. The datasource is created as follows: const dataSource = new OmvDataSour ...

Acquiring and resetting Angular states: A beginner's guide

I'm facing a situation where I need to perform a route jump (essentially a refresh) on the same page, but this jump includes state data. However, even though the state contains valuable information, I am only able to access it through history and cann ...

Error: While working in an Angular project, a TypeError occurs because the property '****' cannot be read when used within a forEach loop

As I attempt to iterate over this.data.members and perform certain actions within the forEach loop on this.addedUsers, I encounter a TypeError: Cannot read property 'addedUsers' of undefined. Interestingly, I can access this.data.members outside ...

The module 'AppModule' is throwing an error with the declaration of 'CacheService'. Make sure to include a @Pipe, @Directive, or @Component annotation to resolve the issue

I'm currently implementing client-side caching in my project by following the code examples from this blog post. After adding the cache.service.ts and http-client.service.ts code, I integrated them into a component that triggers the code. However, I ...

Troubleshooting Problem with Dependency Injection in Angular 2 Services

Within my application, there is a Module that consists of two components: ListComponent and DetailsComponent, as well as a service called MyModuleService. Whenever a user visits the ListComponent, I retrieve the list from the server and store it in the Li ...

The connections between module dependencies are unable to be resolved

I'm encountering an issue with the npm link command. Here's the scenario: I have two Angular apps - 1) app-core (published locally) 2) app-main The app-core module has the following dependencies (installed via npm): core rxjs z ...

Can you explain the functionality of this Angular CLI instruction?

Can you explain the function of this command in the Angular command line? npx ng g s weather --flat false Referenced in: Angular 6 for Enterprise Ready Web Applications, page 61 ...

Issue with 'else if' statement in React Typescript: Unneeded 'else' block following 'return' statement

I am encountering an issue with the else if statement below. Even after removing the last pure Else statement, I am still getting an error on ElseIf from Lint. How can I fix this problem? Error message: Unnecessary 'else' after 'return&apo ...

incorrect choice of ngClass

Having sifted through numerous queries, I have come to this realization... The angular [ngClass] is behaving oddly when it comes to values like 10, 24, and 100. I can't seem to figure out the reason behind this behavior. Perhaps someone here might be ...

Unable to open modal window in Angular 14 micro-frontend application

I've been working on a micro front end project and running into some issues with opening modal popup windows. I've tried both the Angular material and bootstrap approaches, but ran into problems with both. With Angular material, the popup window ...

When transitioning the Next application to Typescript, errors are displayed with JSX, but it functions correctly in the browser

After migrating my Next App from JS to TSX, I noticed that the JSX in my TSX file is showing errors and underlined, even though the app runs fine in the browser. I'm puzzled as to why this inconsistency exists. Can anyone provide assistance in resolvi ...

Angular2: Utilizing multiple slots for transcluded content and passing them to child components as parameters

My current setup includes an article component prefixed with b-... <b-article> Inside this component, I am using custom elements: b-title b-photo b-summary Here is an example of how I am using these elements: <b-article-item> <b-ti ...