简体   繁体   English

Angular 7 Url 更改但没有其他任何反应

[英]Angular 7 Url changes but nothing else happens

This is the first time I post here, I'm quite desperate.这是我第一次在这里发帖,我很绝望。 Im using Angular 7. The problem is that when I manually type the desired url, it works well, but when I press a button and use RouterLink, the url changes but nothing else happens.我使用的是 Angular 7。问题是当我手动输入所需的 url 时,它运行良好,但是当我按下按钮并使用 RouterLink 时,url 发生了变化,但没有其他任何事情发生。 If I press F5, the page will reload and will go to that new URL that has changed without trouble, so it's not a url routing problem.如果我按 F5,页面将重新加载并转到已更改的新 URL,没有问题,因此这不是 url 路由问题。

I only implemented the routerLink in two buttons for the moment (in cities-nav), while I test it.我目前只在两个按钮中实现了 routerLink(在城市导航中),而我正在测试它。 I also implemented a temporary one in app-component.html just in case it was a Material menu problem, but it doesn't work either.我还在 app-component.html 中实现了一个临时的,以防万一它是 Material 菜单问题,但它也不起作用。 Console says nothing.控制台什么也没说。 And I have a console.log inside the onInit of the cities-nav component, which triggers the first time that loads the web, but not when I use routerLink, so it doesn't even get there.我在城市导航组件的 onInit 中有一个 console.log,它在第一次加载网络时触发,但在我使用 routerLink 时不会触发,所以它甚至没有到达那里。 I also tried executing a method with a (click) event.我还尝试使用 (click) 事件执行一个方法。 Doesn't work either.也不行。

My code is the following:我的代码如下:

My app.component.html我的 app.component.html

<div style="text-align:center">
<nav>
<a routerLink="/">Go home</a>
</nav>
</div>
<router-outlet></router-outlet>

This is my app-routing.module这是我的 app-routing.module

import { NgModule } from "@angular/core";
import { Routes, RouterModule } from "@angular/router";
import { CitiesNavComponent } from './cities-nav/cities-nav.component';

const routes: Routes = [
  { path: "", redirectTo: "cities/Madrid", pathMatch: "full" },
  { path: "cities/:name", component: CitiesNavComponent }
];

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

This is my cities-nav.component.html这是我的城市-nav.component.html

    <div class="container">
  <div class="mdl-layout mdl-js-layout mdl-layout--fixed-header">
    <header class="mdl-layout__header">
      <div class="mdl-layout__header-row">
        <span *ngIf="cityName" class="mdl-layout-title">{{this.cityName}}</span>
        <div class="mdl-layout-spacer"></div>
      </div>
    </header>
    <div class="mdl-layout__drawer">
      <span class="mdl-layout-title">Cities</span>
      <nav class="mdl-navigation">
        <a class="mdl-navigation__link" routerLink="/cities/Madrid" routerLinkActive="active">Madrid</a>
        <a class="mdl-navigation__link" routerLink="/cities/Barcelona">Barcelona</a>
        <a class="mdl-navigation__link" (click)="goToCadiz()">Valencia</a>
        <a class="mdl-navigation__link" href="">Cádiz</a>
        <a class="mdl-navigation__link black-text" href="">ABOUT</a>
      </nav>
    </div>
    <main class="mdl-layout__content">
      <div class="page-content"><app-content *ngIf="cityName" [cityName]="this.cityName"></app-content></div>
    </main>
  </div>
</div>

This is my cities-nav.component.ts这是我的城市-nav.component.ts

import { Component, OnInit, NgZone } from "@angular/core";
import { Location } from "@angular/common";
import { ActivatedRoute } from "@angular/router";
import { Router } from "@angular/router";

@Component({
  selector: "app-cities-nav",
  templateUrl: "./cities-nav.component.html",
  styleUrls: ["./cities-nav.component.scss"]
})
export class CitiesNavComponent implements OnInit {
  cityName: string;

  constructor(
    private location: Location,
    private route: ActivatedRoute,
    private router: Router,
    private ngZone: NgZone
  ) {}

  ngOnInit() {
    console.log("Cities nav component OnInit executed");
    this.cityName = this.route.snapshot.paramMap.get("name");
  }
  goToCadiz() {
    this.ngZone.run(() => {
      this.router.navigateByUrl('/cities/Cadiz');
    });
  }
}

First screenshot of tracing Second screenshot of tracing跟踪的一个屏幕截图 跟踪的第二个屏幕截图

Okay, after a long time I found out what was happening.好吧,过了很长时间我才知道发生了什么。 I actually had two problems.我实际上有两个问题。

First one, I had to change this line in cities-nav.component:第一个,我必须在 city-nav.component 中更改这一行:

this.cityName = this.route.snapshot.paramMap.get("name");

To:到:

this.activeRoute.params.subscribe(routeParams => {
  this.cityName = routeParams.name;
  })

Because I always was on the path 'cities/:name', so even if I changed from one city to another, it didn't get the name again from the input.因为我一直在路径 'cities/:name' 上,所以即使我从一个城市更改为另一个城市,它也不会再次从输入中获取名称。 So that subscribe solves the problem, and will give you the new param every time you change the variable inside the same path.这样 subscribe 就解决了问题,并且每次更改同一路径内的变量时都会为您提供新的参数。

The other problem was inside the app-content, because inside onInit I called the cityService which got a city by a name.另一个问题是在 app-content 内部,因为在 onInit 内部我调用了 cityService,它通过一个名字得到了一个城市。 The problem was similar to the other one, it only reached the city once, even if the city input name changed.问题和另一个类似,即使城市输入名称改变,它也只到达城市一次。 So the solution was creating a method ngOnChanges as follows:所以解决方案是创建一个方法 ngOnChanges 如下:

ngOnChanges(changes: SimpleChanges): void {
//Add '${implements OnChanges}' to the class.
this.getCityByName(this.cityName);
}

This way every time the component input 'cityName' changes, it will get the new city and update.这样每次组件输入 'cityName' 改变时,它都会得到新的城市并更新。

console log in the ngOnInit will be called only once.If you want to detect change in the parameters then subscribe to the paraMap in activateRoute. ngOnInit 中的控制台日志只会被调用一次。如果您想检测参数的变化,请订阅 activateRoute 中的 paraMap。

created a sample demo in the link below.在下面的链接中创建了一个示例演示。 https://stackblitz.com/edit/angular-mriyze?file=src%2Fapp%2Fcities-nav.component.ts https://stackblitz.com/edit/angular-mriyze?file=src%2Fapp%2Fcities-nav.component.ts

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM