this.router.navigate() не переходит к URL-адресу

#angular #typescript

#angular #typescript

Вопрос:

У меня есть демонстрационное приложение для разбивки на страницы в Angular. Я ожидаю, что смогу перейти к URL, подобному http://localhost:4200/page/:number . URL-адрес, похоже, меняется в адресной строке URL-адреса браузера, но я должен нажать клавишу Ввода в адресной строке URL-адреса браузера, чтобы фактически перейти к URL-адресу и изменить данные в таблице HTML.

Stackblitz здесь:https://stackblitz.com/edit/angular-225jrs ( HttpErrorResponse это не часть вопроса, но я не знаю, как это исправить в Stackblitz). Вот мой код:

page.component.html:

 <span *ngFor="let x of fakeArray; let index = index">
  <button type="button" class="btn btn-primary" (click)="goToPage(index)">{{ index   1 }}</button>
</span>

<br><br>

<table class="table">
  <thead>
    <tr>
      <th>Alue-ID</th>
      <th>Kunta</th>
      <th>Lääni</th>
      <th>Maakunta</th>
      <th>Seutukunta</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let municipality of municipalities">
      <td>{{ municipality.alue_id }}</td>
      <td>{{ municipality.kunta }}</td>
      <td>{{ municipality.laani }}</td>
      <td>{{ municipality.maakunta }}</td>
      <td>{{ municipality.seutukunta }}</td>
    </tr>
  </tbody>
</table>

<span *ngFor="let x of fakeArray; let index = index">
  <button type="button" class="btn btn-primary" (click)="goToPage(index)">{{ index   1 }}</button>
</span>

<br><br>
  

страница.component.ts:

 import { Component, OnInit } from '@angular/core';
import { MunicipalitiesService } from '../municipalities.service';
import { municipality } from '../municipality.interface';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
  selector: 'app-page',
  templateUrl: './page.component.html',
  styleUrls: ['./page.component.css']
})
export class PageComponent implements OnInit {

  municipalities: municipality[] = [];
  pagenumber: number;
  fakeArray: any;

  constructor(
    private service: MunicipalitiesService, 
    private route: ActivatedRoute,
    private router: Router) { }

  ngOnInit() {
    this.route.params.subscribe(params => {
      this.pagenumber =  params.number;
    })

    this.service.getOneHundredRecords(this.pagenumber).then((data: municipality[]) => {
      this.municipalities = data;
    });

    this.service.getPageCount().then((pageCount: number) => {
      this.fakeArray = new Array(pageCount);
    })
  }

  goToPage = (index: number) => {
    this.router.navigate([`/page/${index}`]);
  }

}
  

municipals.service.ts:

 import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { municipality } from './municipality.interface';

@Injectable()
export class MunicipalitiesService {

  constructor(private http: HttpClient) { }

  getOneHundredRecords = (page: number) => {
    return new Promise((resolve, reject) => {
      this.http.get("/assets/data.json").subscribe((data: municipality[]) => {
        let municipalities = data;
        let index = 0;
        let toBeReturned: municipality[] = [];

        for (let municipality of municipalities) {
          if (index >= (page * 100) amp;amp; index < (page   1) * 100) {
            toBeReturned.push(municipality);
          }
          index  ;
        }
        resolve(toBeReturned)
      })
    })
  }

  getPageCount = () => {
    return new Promise((resolve, reject) =>  {
      this.http.get("/assets/data.json").subscribe((data: municipality[]) => {
        let municipalities = data;
        let index = 0;

        for (let municipality of municipalities) {
          index  ;
        }

        let pageCount = Math.ceil(index / 100);
        resolve(pageCount)
      })
    })
  }

}
  

Комментарии:

1. Технически вы все еще находитесь на том же маршруте к тому же компоненту, поэтому он не перезагружается. Вы можете принудительно перезагрузить, выполнив это: this.router.navigate([ /page/ ${index} ]).then(() => window.location.reload()); однако я бы посоветовал сделать это, потому что это в основном удалило все ваши состояния. Поэтому вместо этого navigate будет лучше, если вы получите данные нового набора с помощью goToPage() метода.

Ответ №1:

В Angular router существует политика, которая запрещает вам, когда вы хотите перейти к тому же маршруту, что и тот, по которому вы находитесь в данный момент. Вы могли бы использовать RouteReuseStrategy следующим образом:

страница.component.ts:

 ***

constructor() {
    this.router.routeReuseStrategy.shouldReuseRoute = () => false;
}

***
  

Это позволит вашему компоненту обновиться после того, как вы перейдете по нему (из нее).

Надеюсь, это поможет!

Комментарии:

1. Вы спасли меня, мне потребовалось около двух дней, чтобы заставить его работать! Но теперь модальное окно открывается дважды. Но, возможно, это некоторые из ошибок нашего приложения.

2. Рад, что смог помочь 🙂

3. Мааан… Я потратил более 13 часов, пытаясь заставить это работать, и когда я собирался сдаться, я нашел ваше решение, и оно сработало! Большое спасибо!!!