为什么 Angular 总是重定向到主页?

Why Angular always redirecting to main page?

我总是尝试获取 '/' 它显示 static-root-component(我的主页的组成部分), 但是当它是 '/welcome' 页面时立即重定向到 '/' 并且还加载 static-root-component 而不是 welcome-component

最初我想在未授权的情况下将用户重定向到欢迎页面,但只能在 JavaScript 中检查登录状态。在 JS 获得有关登录状态的信息后,它决定使用 location.replace("/welcome") 重定向,但是...... Angular 再次转到 '/'

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

我不知道出了什么问题还有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 { }

如果需要,我可以删除任何其他 Angular 文件

在你的代码中,像下面这样改变

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

在组件文件中,像下面这样注入

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

当你想要导航时使用下面的代码而不是 location.replace("/welcome")

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

我的项目基于 MEAN(Mongo、Express、Angular 和 NODEJS)...最后一个是问题的根源

@Shakthifuture,你说你想看完整代码,我开始回答:

“你还想看什么?我的数据和服务器文件不影响...”

我开始思考“如果影响会怎样?”:整个项目中的路由通过 Angular 工作,但所有新的站点连接都通过 NodeJS 和 Express,所以我忘记了 404个案例...

问题:

很久以前,在项目根文件夹的服务器脚本文件 index.js 中,我添加了有关如果找不到输入的路径该怎么办的代码:

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

及以上类似:

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

'/welcome' 什么都没有,这就是重定向发生的原因

解决方案:

让我们添加 '/welcome' 处理程序:

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

(再次 index.html 由于 SPA)

检查您尝试在链接到的 Componentconstructor 中实例化的 Module您正尝试访问的路由路径

在这种情况下:

我们的组件: example.component.ts

我们的模块: 包含HttpClient

的HttpClientModule

我们的路由路径: "/example"

并确保 Module 已经存在于 app.module.ts 中,这里是一个例子:


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) { }
}

现在让我们看看有和没有模块导入的应用模块示例,看看区别


app.module.ts

不在导入数组中包含 HttpClientModule


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

在导入数组中包含 HttpClientModule


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.

如果这是你的情况,那肯定会解决你的问题,除非你有其他强制重定向到主页“index.html”或任何其他路径的东西,否则如果那不能解决你的问题,请阅读以下内容备注:

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: '' }
];

只能这样

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