首页 > 解决方案 > 离子角 nbOnInit 未定义?

问题描述

我对离子有问题。我想把页数放在 ngOnInit 的函数中,但是写的是 undefined

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { HttpConfigService } from '../services/http-config.service';
import { GeolocationService } from '../services/geolocation.service';
@Component({
  selector: 'app-commerces',
  templateUrl: './commerces.page.html',
  styleUrls: ['./commerces.page.scss'],
})
export class CommercesPage implements OnInit {

  url: string;
  itemListData = [];
  page_number = 1;
  page_limit = 8;
  isFinish = false;
  nbPages;

  constructor(
    private httpConfigService: HttpConfigService,
    private httpClient: HttpClient,
    private geolocationService: GeolocationService
  ) {
  }

  ngOnInit() {
    this.nbPages();
    this.getCommerces(true, "");
  }

  doInfinite(event) {
    this.nbPages();
    this.getCommerces(true, event);
  }

  sort() {
    this.itemListData.sort((a, b) => {
      if (a.title.rendered > b.title.rendered) {
        return 1;
      } else if (a.title.rendered < b.title.rendered) {
        return -1;
      } else {
        return 0;
      }
    });
  }

  onSearchChange(event) {
    console.log(event.detail.value);
  }


  npPage() {
    this.httpClient
      .get('https://exemple.fr/wp-json/wp/v2/listing', { observe: 'response' })
      .subscribe((data: any) => {
        // Here, resp is of type HttpResponse<MyJsonData>.
        // You can inspect its headers:
        this.nbPages = data.headers.get('X-WP-TotalPages');
      });
  }

  getCommerces(isFirstLoad, event) {
    for (let j = 1; j < this.nbPages; j++) {
      this.httpClient
        .get('https://exemple.fr/wp-json/wp/v2/listing?page=' + j, { observe: 'response' })
        .subscribe((data: any) => {
          for (let i = 0; i < data.body.length; i++) {
            data.body[i].location = this.geolocationService.getDistance(data.body[i]._geolocation_lat, data.body[i]._geolocation_long).toFixed(2);;
            data.body[i]._gallery = data.body[i]._gallery[Object.keys(data.body[i]._gallery)[0]]
            this.itemListData.push(data.body[i]);
          }

          if (isFirstLoad)
            event.target.complete();

        }, error => {
          console.log(error);
        })
    }
    this.sort();
    console.log(this.itemListData);
  }
}

nbPages 未定义,我需要此变量在 getCommerces() 中执行循环

你能帮我找出问题所在吗,Angular 对我来说是新的,在 ngOnInit 中不可能改变变量的值?

标签: angulartypescriptionic-framework

解决方案


您需要在您的类定义上实现 OnInit:

export class YOURCLASSNAME implements OnInit {

您正在调用一个函数:nbPages()

但你的功能被定义为:(没有最后的s)

npPage() {

推荐阅读