Why Angular always redirecting to main page?

Viewed 1464

Always I trying to GET '/' it shows static-root-component (component of my main page), but when it is '/welcome' page immediately redirecting to '/' and also loading static-root-component instead of welcome-component

Initially I wanted to redirect users to welcome page if they aren't authorized, but login status only can be checked within JavaScript. After JS got info about login status it decides to redirect using location.replace("/welcome"), but... Angular again goes to '/'

"Funny" fact: there isn't any routing problems during debug with ng serve but it always happens with ng build

I don't know what's gone wrong and there is app.module.ts:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { StaticRootComponent } from './static-root/static-root.component';
import { WelcomeComponent } from './welcome/welcome.component';
import { HttpClientModule } from '@angular/common/http';
import { HttpService } from './http.service';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

const appRoute: Routes = [
  { path: '', component: StaticRootComponent, pathMatch: 'full' },
  { path: 'welcome', component: WelcomeComponent }
];

@NgModule({
  declarations: [
    AppComponent,
    StaticRootComponent,
    WelcomeComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    RouterModule.forRoot(appRoute),
    HttpClientModule
  ],
  providers: [HttpService],
  bootstrap: [AppComponent]
})

export class AppModule { }

I can drop any other Angular file if needed

3 Answers

In your code, change like below

const appRoute: Routes = [
  { path: '', component: StaticRootComponent },
  { path: 'welcome', component: WelcomeComponent },
  { path: '**', redirectTo: '' }
];

In the component file, inject this like below

import { Router } from '@angular/router';
constructor(
        private router: Router
) {}

When you want do navigation use the below code instead of location.replace("/welcome")

this.router.navigate(['/welcome']);

My project based on MEAN (Mongo, Express, Angular and NODEJS)... The last was a source of problem

@Shakthifuture, you said you want to see full code and I started answering:

"What you wanna to see else? My data and server files doesn't affec..."

and I've starting think "what if affect?": routing in whole of project works by Angular, but all new connection to the site pass NodeJS and Express, so I forgot about 404 case...

THE PROBLEM:

In server script file index.js of project's root folder a long time ago I've added code about what to do if entered path not found:

app.use(function (req, res, next) {
    res.redirect('/');
    // IF 404 NOT FOUND
});

and above of it something like:

app.get('/', function (req, res) {
    res.sendFile(`${__dirname}/angular/index.html`)
});
// send index if path is '/'

but nothing for '/welcome', that's why redirecting happens

THE SOLUTION:

let's add the '/welcome' handler:

app.get('/welcome', function (req, res) {
    res.sendFile(`${__dirname}/angular/index.html`)
});

(again index.html due to SPA)

Check the Module you trying to instantiate in the constructor of the Component linked to the Routing Path you are trying to access

In this case:

Our Component: example.component.ts

Our Module: HttpClientModule that contains HttpClient

Our Routing Path: "/example"

and make sure that Module is already existing in the app.module.ts , here is an example:


example.component.ts


import {HttpClient} from '@angular/common/http'; //child of HttpClientModule 

@Component({selector: 'app-example',templateUrl: './example.component.html', styleUrls: ['./example.component.css']})

export class ExampleComponent{
  constructor(private httpClient: HttpClient) { }
}

now let's see both examples of app module with and without the Module import and see the difference


app.module.ts

Without including HttpClientModule in imports array


import { AppComponent } from './app.component';

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

In this case loading the "/example" path will redirect you to the main page path which is usually "/" and that's because example.component.ts is using HttpClient (child of HttpClientModule) but not finding it in app.module.ts .


app.module.ts

Including HttpClientModule in imports array


import { AppComponent } from './app.component';
import { HttpClientModule} from '@angular/common/http'; //Import that module you willing to use

@NgModule({
  declarations: [...],
  imports: [BrowserModule,HttpClientModule,...], //add the module we currently using
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

In this case loading the "/example" path will work properly since we added the required module in app.module.ts.

If that's your case that would definitely fix your problem unless you have something else forcing the redirection to home page "index.html" or any other path, else if that didn't fix your problem read the following notes:

Make sure to check there are no redirections in the app-routing.module.ts routes array like this

const routes: Routes = [
    {path: 'example', component: ExampleComponent},
    { path: '/example', redirectTo: '' }
];

it should only be like so

const routes: Routes = [
    {path: 'example', component: ExampleComponent}
];

Also make sure there is no routing behaviour causing the redirection like @angular/router through something like this.router.navigate(['/'])

PS: SAME ISSUE COULD IMPLY IF YOU USING A SERVICE THAT'S USING A MODULE WHICH IS NOT ADDED TO MODULE IMPORTS IN app.module.ts

Related