路由总是重新加载页面。

10
当我使用组件之间的路由导航时,Angular总是重新加载应用程序。事件顺序如下:
  • 加载主页(localhost:4200)
  • 重定向到位置(localhost:4200/locations)
  • 单击按钮路由到(localhost:4200/items/1)
  • 显示项目页面
  • 然后它自动路由到(localhost:4200/#)[我该如何阻止它这样做?]
  • 然后它又路由回位置(localhost:4200/locations)
对于为什么它不能停留在项目页面,你有什么想法吗?我一直在疯狂地思考(剩下的头发),试图弄清楚这个简单的用户错误。此外,在Chrome控制台或WebStorm终端中没有错误。我使用的是Angular 4.2.4。
以下是我的组件:

AppModule

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

import {AppComponent} from './app.component';
import {LocationComponent } from './location/location.component';
import {ItemsComponent } from './items/items.component';

import {AppRoutingModule} from './app-routing.module';

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

AppRouting

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

import { ItemsComponent } from './items/items.component';
import {LocationComponent} from './location/location.component';

const routes: Routes = [
  { path: 'locations',  component: LocationComponent },
  { path: 'items/:id',  component: ItemsComponent },
  { path: '', redirectTo: '/locations', pathMatch: 'full' }
];

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

AppComponent
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `<div>Hello</div><router-outlet></router-outlet>`
})
export class AppComponent { }

位置组件
import {Component, OnInit} from '@angular/core';
import {LocationModel} from './location.model';
import {Router} from '@angular/router';

@Component({
  templateUrl: './location.component.html',
  styleUrls: ['./location.component.css']
})
export class LocationComponent implements OnInit {

  locations: LocationModel[];
  location: LocationModel;

  constructor(private router: Router) {
    this.locations = [
      {id: 1, name: 'Loc1'},
      {id: 2, name: 'Loc2'},
      {id: 3, name: 'Loc3'},
      {id: 4, name: 'Loc4'}
    ];
  }

  ngOnInit() {
  }

  onSelect(loc: LocationModel): void {
    this.location = loc;
    console.log('onSelect for loc.id[' + this.location.id + ']');
    window.alert('onSelect for loc.id[' + this.location.id + ']');
    this.router.navigate(['/items', this.location.id]);
  }
}

位置 - HTML
<nav class="navbar navbar-fixed-top">
  <a class="navbar-brand" href="do_nothing">CO_ICON</a>

  <div class="nav navbar-nav">
    <a class="nav-item nav-link active" href="do_nothing">
      <div>Add</div>
    </a>
  </div>
</nav>

<div class="container">
  <div class="row">
    <div class="col-md-3">
      <!-- /.card -->
      <div class="card" *ngFor="let location of locations" (click)="onSelect(location)">
        <div class="card-block">
          <div class="list-group">
            <a href="do_nothing" class="list-group-item">{{location.name}}</a>
          </div>
        </div>
      </div>
      <!-- /.card -->
    </div>
  </div>

商品组件
import 'rxjs/add/operator/switchMap';
import { Component, OnInit } from '@angular/core';
import {ItemModel} from './item.model';
// import {ItemService} from './item.service';
import {ActivatedRoute, ParamMap} from '@angular/router';

@Component({
  templateUrl: './items.component.html',
  styleUrls: ['./items.component.css']
})
export class ItemsComponent implements OnInit {

  items: ItemModel[];

  constructor(
    // private itemService: ItemService,
    private route: ActivatedRoute) {
    console.log('constructed ItemsComponent');
    // window.alert('constructed ItemsComponent');
    this.items = [
      {id: 1, location: 1, name: 'Item 1', quantity: 1},
      {id: 2, location: 1, name: 'Item 2', quantity: 2},
      {id: 3, location: 2, name: 'Item 3', quantity: 1},
      {id: 4, location: 1, name: 'Item 4', quantity: 2}
    ];
  }

  ngOnInit() {
    // this.route.paramMap
    //   .switchMap((params: ParamMap) => this.itemService.getItems(+params.get('id')))
    //   .subscribe(list => this.items = list);

    console.log('ngOnInit for is with 1 - A');
    window.alert('ngOnInit for is with 1 - A');
  }

}

项目 - HTML
<nav class="navbar navbar-fixed-top">
  <a class="navbar-brand" href="do_nothing">CO_ICON</a>

  <div class="nav navbar-nav">
    <a class="nav-item nav-link active" href="do_nothing">
      Add Item
    </a>
  </div>
</nav>

<div class="container">
  <div class="row">
    <div class="col-md-3">
      <!-- /.card -->
      <div class="card" *ngFor="let item of items">
        <div class="card-block">
          <div class="list-group">
            <a href="do_nothing" class="list-group-item">{{item.name}}</a>
          </div>
        </div>
      </div>
      <!-- /.card -->
    </div>
  </div>

任何帮助都非常感激!谢谢!Chris....

尝试移除 href="#",这会导致应用程序重新加载。如果您需要哈希值,请尝试使用 Angular 的片段指令。 - LLai
啊 - 这就是问题的关键。我没有任何 #。Angular 自动完成了这个操作。有什么想法可以去除它或者是否有配置指令可以设置? - Chris
你的锚点标签中没有像你发布的HTML中那样的href="#"吗? - LLai
1
谢谢 - 你说得完全正确!那个方法可行。 - Chris
3个回答

22

请从锚点标签中删除 href="#"。原生的HTML href 属性会导致Angular重新加载。Angular导航应由路由指令和服务处理。


在上面的代码中,我用 do_nothing 替换了 #。但是没有起作用 - 所以在我的代码中,我完全删除了 <a> 标签,这样就可以了。以防万一有人想让上面的代码工作。LLai - 再次感谢。你在 15 秒内解决了我不幸花费了 2 小时的问题。 - Chris
1
不是 '#' 导致你的页面重新加载,而是 href 属性。你应该删除 href 属性,并像我在 我的回答 中解释的那样使用 routerLink 指令。 - Filip Savic

18

正如LLai在他的回答中所说,为了避免重新加载页面,你应该不要使用<a>标签的href属性,而是使用AngularRouter和他的routerLink指令。

因此,从你的<a>标签中删除href属性并像这样使用routerLink

<a class="list-group-item" [routerLink]="['login']"></a>

干杯。:)


-2
将javascript:;添加到链接href中... 这样做不会立即使页面滚动到顶部,也不会在使用哈希时炸掉您的路由器。

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