【问题标题】:Why Angular always redirecting to main page?为什么 Angular 总是重定向到主页?
【发布时间】:2021-11-09 09:36:54
【问题描述】:

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

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

“有趣”的事实:在使用ng serve 进行调试期间没有任何路由问题,但在使用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, pathMatch: 'full' }, { path: '/welcome', component: WelcomeComponent } ];
  • 分享完整代码。
  • @milan,显然我试过了,但编译器说:Invalid configuration of route '/welcome': path cannot start with a slash
  • 您是否尝试先添加welcome 路由?
  • @Shakthifuture,你想看什么文件?我用ng new 生成了项目并且没有编辑其他文件

标签: javascript node.js angular angular-ui-router


【解决方案1】:

在您的代码中,更改如下

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']);

【讨论】:

  • 检查过了。页面仍然重定向到'/',至于this.router.navigate(['/welcome']);,我说导航必须由一些脚本控制。如果只能从 TS 路由,那么我认为如何从 JS 调用 Angular,我在编辑某些 TS 文件时在我的代码中犯了错误,以便证明/反驳它我将重新生成新的 ng 项目并零碎整个我的代码
  • 我做到了,检查
【解决方案2】:

在链接到您的路由路径组件构造函数中检查您尝试实例化的模块正在尝试访问

在这种情况下:

我们的组件: 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 { }

在这种情况下,加载“/example”路径会将您重定向到通常为“/”的主页路径,这是因为 example.component.ts 正在使用 HttpClientHttpClientModule 的子级),但在 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 { }

在这种情况下,加载“/example”路径将正常工作,因为我们在 app.module.ts 中添加了所需的模块。

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

确保检查 app-routing.module.ts 路由数组中没有像这样的重定向

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

应该只是这样

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

还要确保没有路由行为导致像 @angular/router 这样的重定向,通过类似 this.router.navigate(['/'])

PS:如果您使用的服务使用的模块未添加到 app.module.ts

中的模块导入中,则可能会出现同样的问题

【讨论】:

    【解决方案3】:

    我的项目基于 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)

    【讨论】:

      猜你喜欢
      • 2020-06-14
      • 1970-01-01
      • 1970-01-01
      • 2016-12-22
      • 2016-10-02
      • 2017-06-11
      • 2014-07-10
      • 2018-02-11
      相关资源
      最近更新 更多