Discovering the ASP.NET Core HTTP response header in an Angular application using an HTTP interceptor

I attempted to create a straightforward app version check system by sending the current server version to the client in the HTTP header. If there's a newer version available, it should trigger a notification for the user to reload the application. Initially, I believed this would be a simple task, but my Angular interceptor is not capturing the new response header sent by ASP.NET Core. My setup involves using .NET 6 and Angular 13.

Startup.cs

app.Use(async (context, next) =>
{
   context.Response.Headers.Add("X-AppVersion", Assembly.GetEntryAssembly()!.GetName().Version!.ToString());
   await next();
});

app.UseSpa(spa =>
        {
            spa.Options.SourcePath = "ClientApp";
            spa.Options.DefaultPageStaticFileOptions = new StaticFileOptions
            {
                OnPrepareResponse = context =>
                {
                    var headers = context.Context.Response.GetTypedHeaders();
                    headers.CacheControl = new CacheControlHeaderValue
                    {
                        NoCache = true,
                        NoStore = true,
                        MustRevalidate = true,
                        MaxAge = TimeSpan.Zero
                    };
                    // Uncertain about this component
                    headers.Append("X-AppVersion", Assembly.GetEntryAssembly()!.GetName().Version!.ToString());
                }
            };
        });

Angular interceptor

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
   const reqWithCredentials = req.clone({ withCredentials: true });
   return next.handle(reqWithCredentials).pipe(
    map(resp => {
      if (resp instanceof HttpResponse) {
        if (resp.headers.get('x-appversion')) {
          console.log(resp.headers.get('x-appversion'));
        } else {
          console.log(null); // The result is consistently null
        }
        return resp;
      }
    })
  )
}

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

An error in TypeScript has occurred, stating that the type 'IterableIterator<any>' is neither an array type nor a string type

Hey there! I'm currently working on an Angular project and encountering an error in my VS Code. I'm a bit stuck on how to fix it. Type 'IterableIterator<any>' is not an array type or a string type. Use compiler option '- ...

What is the best way to incorporate vertical scrolling into a React material table?

I'm having trouble getting vertical scroll to work with my material table in React Typescript. Horizontal scroll is functioning properly for large data, but I'm stuck on implementing the vertical scroll. Here's my code: {isLoading ? ...

Steps for determining if a string is compatible with a user-defined type in Typescript

Just getting started with Typescript and currently working on a sudoku game. Here are the types and interface I have set up: export type GridCellValue = 1|2|3|4|5|6|7|8|9; export interface GridCell { readonly: boolean, value: GridCellValue|null, } ex ...

Exploring Angular 7: A guide to implementing seamless pagination with routing for fetching API data

I am new to Angular and I would like some assistance. I need to modify the Route URL http://my_project/products/page/3 when the page changes. The API server provides data through paging, with URLs structured like http://apiserver/product/[limet]/[offset] ...

Tips for effectively mocking a service class in a hybrid Angular project to facilitate unit testing

I'm currently working on a hybrid Angular project, but I've encountered some challenges with unit testing. Despite trying out this solution, it doesn't seem to be effective for my particular project. I keep receiving an error when running ...

The combination of [(ngModel)] and name is not compatible with angular's ng-autocomplete feature, causing it to malfunction

I'm currently integrating ng-autocomplete with Angular 8, and encountering an issue. Here is the code snippet: HTML: <div class="field"> <label class="label">Nombre del condominio:</label> <div class="control"> ...

Next.js production build encountering an infinite loading error

I have been utilizing the Next.js TypeScript starter from https://github.com/jpedroschmitz/typescript-nextjs-starter for my current project. The issue I am facing is that when I attempt to build the project after creating numerous components and files, it ...

What is the process for converting inline SVG images on the server?

Looking to use inline SVG as a background-image for another element? Check out this example that currently only works in Chrome. If you need an alternative method, take a look at the simpler inline SVG from the RaphaelJS demo here. <svg height="480" ve ...

Prevent time slots from being selected based on the current hour using JavaScript

I need to create a function that will disable previous timeslots based on the current hour. For example, if it is 1PM, I want all timeslots before 1PM to be disabled. Here is the HTML code: <div class=" col-sm-4 col-md-4 col-lg-4"> <md ...

Troubleshooting ngModel Binding Issue with Sub-Children in CKEditor 5 and Angular 7

Firstly, I am sharing my code below: ListPagesComponent: export class ListPagesComponent { public model = { id: -1, actif: 0, link: '', htmlContent: { fr: '', ...

Utilizing getServerSideProps in the new app router (app/blah/page.tsx) for maximum functionality

I am a beginner in Next.js and I am currently experimenting with the new app router feature by placing my pages under app/.../page.tsx The code snippet provided works when using the page router (pages/blah.tsx) but encounters issues when used in app/blah/ ...

Typescript encounters an overload error on the Accumulator argument while using reduce operation

I encountered the following code snippet: const foo = ( fields: { [key: string]: string, } ) => { const { one, two } = Object.values(fields).reduce( (acc, field) => { if (isOne(field)) { return { ...acc, two: [...acc.two, ...

The express application's GET route is causing a "Cannot GET" error to be thrown

I am managing different types of pages: the main root page (/) today's chapter page (/929 OR /929/) which eventually redirects to /929/<CHAPTER> where <CHAPTER> is a natural number between 1 to 929 individual chapter pages (/929/<CHAP ...

Jodit-React: Addressing the Placeholder Problem

I've recently incorporated Jodit-react into my react-typescript project, but I encountered an error when adding the config property. The error message stated that it "Has no property common with type." Unfortunately, I'm unsure why this is happe ...

Is there a way to activate Apache Proxy Cache for error status responses such as 403 or 404?

We have successfully implemented Apache Web Server (HTTPD) as a proxy for the Angular Universal (SSR) app. The caching functionality is working well when the Angular App responds with a status code of 200, as confirmed by the X-Cache: HIT from <url> ...

How can you store form field validation rules (for example, firstname.dirty) in an array within TypeScript in Angular?

How do I save form field validation rules in an array? What should replace /'''''HERE'''''/ with? formfields: Array<Object> = [ {label: "Employer:", control: "employer", val ...

Unable to place value into an array following the invocation of a function in Angular 9

Within an array I established, I am encountering an undefined value when I use console.log. Take a look at my component.ts below: export class OrderExceptionReportComponent implements OnInit { public sessionData: ExceptionReportSessionData[] = []; n ...

The issue with the Bootstrap 5 navbar in an Angular project is that it expands properly but fails to close when

I am currently working on developing a Single Page Application using Angular 12 and Bootstrap 5. As part of this project, I have created a shared navbar component. The issue I am facing is that when the navbar transitions to the hamburger menu button for ...

Comparing hashed passwords in C# using Pbkdf2 encryption

Currently working on an authentication system in .Net Core where I have an API to create a user with a login and password. After hashing the password, I'm struggling to find a way to compare the hashed password with the new input provided by the user ...

Accessing the URL causes malfunctioning of the dynamic routing in Angular 2

I am currently working on implementing dynamic routing functionality in my Angular application. So far, I have successfully achieved the following functionalities: Addition of routing to an existing angular component based on user input Removal of routin ...