Angular7, paginate.Я не могу загрузить страницы в компоненте - PullRequest
0 голосов
/ 20 февраля 2019

Я начинаю с angular. У меня есть проект, в котором я делаю запросы к бэкэнду, эти запросы возвращают данные свойств, скажем, около 2000 результатов.Бэкэнд облегчает пейджинг для меня, я делаю только запрос POST и в теле я пропускаю нужную страницу.Я имею в виду два компонента, один из которых показывает карточки с данными, а другой - страницу, у меня также есть сервис, который я покажу вам позже. Страница работает хорошо, где-то в моей логике происходит сбой, потому что мой компонент, в котором у меня есть данные, не обновляет новую страницу. Я уже извиняюсь за мой английский, он совсем не хорош.Я оставляю вам код шаблона, компонентов и сервиса.Спасибо.

[DataTemplate]

<!--SPINER-->
<div class="spinner-border text-info" role="status" *ngIf="loading">
  <span class="sr-only">Loading...</span>
</div>
<!-- RESULTS-->
<div class="result-area" *ngIf="!result && !loading">
  <img
    class="icon"
    src="../../assets/Content/Images/no-result-icon.png"
    alt=""
  />
  <section>
    <h1 class="ng-binding">No existen resultados para los filtros escogidos</h1>
    <p class="ng-binding">
      Modifica tu elección de filtros para buscar entre <br />nuestras
      propiedades
    </p>
  </section>
</div>
<!-- !RESULTS -->
<div class="result-area">
  <div class="card-columns row" *ngIf="result">
    <span class="col-12">Total de propiedades: {{this.resultnum}}</span>
    <div class="card col-3" *ngFor="let i of fullData" >
      <img src="../../../../assets/Content/Images/default-img.png" class="card-img-top" alt="..." />
      <div class="card-body">
        <h5 class="card-title">{{i.PropertyType}}</h5>
        <p class="card-text">
        <span>
          {{i.MunicipalityName + "," + i.NeighborhoodName}}
          <br><small class="text-muted">{{i.TotalArea}} m²</small>
        </span>
      </div>
    </div>
        <app-paginator></app-paginator>
  </div>
</div>

[DataComponent]

import { Component, OnInit } from "@angular/core";
import { PropiedadesService } from "src/app/Services/propiedades-service.service";

@Component({
  selector: "app-result-area",
  templateUrl: "./result-area.component.html",
  styleUrls: ["./result-area.component.css"]
})
export class ResultAreaComponent implements OnInit {
  result = false;
  loading = true;

  resultnum = 0;
  fullData: any;

  filtrosActivos: any[] = [];
  constructor(private _PropiedadesService: PropiedadesService) {}

  ngOnInit() {
     this.loadData();
 }
  loadData() {
    this._PropiedadesService.postSearchResult().subscribe((res: any) => {
      this.fullData = res.Result.Properties;
      this.loading = false;
      if (res.Result.Count > 0) {
        this.result = true;
        this.resultnum = res.Result.Count;
      }
    });
  }
}

[PaginationTemplate]

<ul class="pagination">
  <li class="page-item"><a class="page-link cursor-pointer" (click)="setPage(actualpage - 1)" >Previous</a></li>
  <li class="page-item" *ngFor="let i of fullData; let idx = index"><a class="page-link cursor-pointer" (click)="setPage(idx + 1)">{{idx+1}}</a></li>
  <li class="page-item"><a class="page-link cursor-pointer" (click)="setPage(actualpage - 1)" >Next</a></li>
</ul>

[PaginationComponent]
import { Component, OnInit, Output } from '@angular/core';
import { PropiedadesService } from 'src/app/Services/propiedades-service.service';

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

  allpages: any[];
  maxpages: number;
  @Output() actualpage: number;
  fullData: any;
  constructor(private propiedadesService: PropiedadesService) { }

  ngOnInit() {
    this.propiedadesService.postSearchResult()
    .subscribe((res: any) => {
      this.fullData = res.Result.Properties;
      this.maxpages = res.Result.Count;
      console.log(this.maxpages);
    });
  }
  setPage(page: number) {
     this.propiedadesService.pagSelected = page;
     this.actualpage = page;
     this.propiedadesService.postSearchResult();
     console.log(
       `Pagina anterior: ${this.actualpage - 1}
        - Pagina actual ${this.propiedadesService.pagSelected}
        - Pagina siguiente ${this.actualpage + 1 }`);
  }

}

[Служба]

import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { EventEmitter } from 'protractor';

@Injectable({
  providedIn: "root"
})
export class PropiedadesService {

  pagSelected = 0;

  /* FILTROS */
  private pourURL = "http://localhost:51654/api/v1/Purposes?lang=es";
  private muniURL = "http://localhost:51654/api/v1/Municipalities?lang=es";
  private typesURL = "http://localhost:51654/api/v1/PropertyTypes?lang=es";

  /* POST REQUEST DATA*/
  private searchResult = "http://localhost:51654/api/v1/MainSearch";


  /* REQUEST BODY */
  pagBody: any = {
    "Neighborhoods": [],
    "Page": this.pagSelected
  };

  constructor(private http: HttpClient) {}

  getPurposes() {
    return this.http.get( this.pourURL );
  }
  getMunicipalities() {
    return this.http.get( this.muniURL );
  }
  getTypes() {
    return this.http.get( this.typesURL );
  }
  postSearchResult() {

    return this.http.post(this.searchResult, this.pagBody);
  }

}
...