Angular 中的 routerLink 不起作用

5
我正在使用TypeScript学习Angular JS。我有Angular JS的经验,但是当它与TypeScript集成时,对我来说完全是新的。我现在正在为我的应用程序配置路由。
This is my app.module.ts file
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { DirectoryComponent } from './directory/directory.component';
//import { AppRoutingModule }  from './app-routing.module';



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



const routes: Routes = [
{
  path: '',
  component: HomeComponent
},
{
  path : 'directory',
  component : DirectoryComponent
}
];



@NgModule({
  declarations: [
  AppComponent,
  HomeComponent,
  DirectoryComponent,

  ],
  imports: [
  BrowserModule,
  FormsModule,
  HttpModule,
  RouterModule.forRoot(routes)
  ],
  providers: [ ],
  bootstrap: [AppComponent]
})
export class AppModule { }

我在那个文件中配置了路由。当我直接从浏览器访问路由时,它可以正常工作。然后我尝试在app.component.html中添加链接。 这是我的app.component.html

<h1>
  {{title}}
</h1>

<div>
    <ul>
        <li>
            <a [routerLink]="['/']">Home</a>
        </li>
        <li>
            <a [routerLink]="['directory']">Directory</a>
        </li>
    </ul>
</div>

<div>
    <router-outlet></router-outlet> 
</div>

然后我点击链接。两个链接都完全不起作用。但是当我直接在URL栏中输入路由值进行访问时,它可以工作。我的HomeComponent和DirectoryComponent很简单。它们只是显示一条消息。
当我首次访问“/directory”网址时,它可以工作。它显示目录页面。从那里,当我点击home链接时,它会更新到主页。但是URL仍然是“directory”。但是当我再次点击目录链接时,什么都没有发生。
我遵循了这些解决方案 routerLink is not working in angular 2 routerlink not working in angular2 RouterLink does not work 所有的都不起作用。
我检查了HTML元素,它正确地呈现了链接。问题在于我点击链接时什么都没有发生。

enter image description here

我正在使用最新版本的Angular JS。我的代码有什么问题?

你收到了哪个消息? - Swanand Taware
我没有收到任何消息。当我第一次访问“/directory”网址时,它是有效的。它显示目录页面。从那里,当我点击主页链接时,它会更新到主页。但是网址仍然是“directory”。但是当我再次点击目录链接时,什么也没有发生。可能出现了什么错误?问题出在哪里? - Wai Yan Hein
从 '[routerLink]' 和 '[directory]' 以及 ['/'] 中删除方括号。 - Swanand Taware
3个回答

0

这是因为家目录更改了,将routerlink更改为其他名称即可解决问题。

不要使用'',使用一些名称代替。


什么?我不明白。你能具体解释一下吗? - Wai Yan Hein
对于Home组件的路由路径,请放置一些字符串而不是空字符串。 - Vinay Kumar
不,它已经在当前目录中了。所以,将其放置在“/home”之类的位置。 - Vinay Kumar

0

我遇到了同样的问题,结果发现如果路由不存在,路由将不起作用。我有

<nav>
    <a routerLink="/review" >Full reviews</a>
</nav>

但我的路由设置为review(没有s)
希望这能帮助其他人


0
对我来说,问题出在我没有在app.module.ts的declarations中导入该组件。
@NgModule({
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    ReactiveFormsModule,
    HttpClientModule,
    AppRoutingModule,
  ],
  declarations: [
    //make sure your components are declared here
    ResetPasswordConfirmedComponent,
  ],

接下来确保你将路由器引入组件中,这样它就能正常工作了!

供参考,我正在使用 Angular 15。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接