Home > Software design >  Angular Single Page Application fetching data from server every time it goes to a new Route
Angular Single Page Application fetching data from server every time it goes to a new Route

Time:08-14

My simple Angular Single Page application has two components. I have defined a route for each of these components. If I click on a link, corresponding component should be displayed in the view.

Router

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { CompAComponent } from './comp-a/comp-a.component';
import { CompBComponent } from './comp-b/comp-b.component';
 
const routes: Routes = [
  {
    path: 'componentA', component: CompAComponent
  },{
    path: 'componentB', component: CompBComponent
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

HTML

<div >
<div >
    <ul>
        <li><a href="testApp/componentA">componentA</a></li>
        <li><a href="testApp/componentB">componentB</a></li>
    </ul>
</div>
<div >
    <router-outlet></router-outlet>
</div>

</div>

App.Module

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { CompAComponent } from './comp-a/comp-a.component';
import { CompBComponent } from './comp-b/comp-b.component';

@NgModule({
  declarations: [
    AppComponent,
    CompAComponent,
    CompBComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

This application is working but every time I click on a link, it is fetching all the JS files from the server. Shouldn't a single page application get all the required files from server during initial loading?

I added 'testApp' in the href since this application has a context path of 'textApp' in the head of index.html file like <base href="/testApp"> enter image description here

CodePudding user response:

Angular needs to do some stuff behind the scenes to tell the browser how to handle links within the SPA. So you should use the attribute routerLink on your links instead of href so Angular knows which links are SPA-links.

<div >
<div >
    <ul>
        <li><a routerLink="/componentA">componentA</a></li>
        <li><a routerLink="/componentB">componentB</a></li>
    </ul>
</div>
<div >
    <router-outlet></router-outlet>
</div>

</div>

More info: https://angular.io/guide/router-tutorial#control-navigation-with-ui-elements

  • Related