首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >无法分配引用到另一个模块的静态上下文的值(尝试分配时未定义)

无法分配引用到另一个模块的静态上下文的值(尝试分配时未定义)
EN

Stack Overflow用户
提问于 2019-06-24 06:38:37
回答 2查看 86关注 0票数 0

我正在尝试做一个离子应用程序,为了让我的代码更有条理,我考虑将某些东西分离到其他模块中并导入它们,问题是当我将另一个模块中的静态变量分配给我试图导入它的模块时,我变得“未定义”。

我尝试将导出的模块设置为静态的,因此module.ts (我手动完成的)如下所示:

代码语言:javascript
复制
/*--------- Menu options---------*/
代码语言:javascript
复制
    export class AppPages{

      public static pages = [

        {
          title: 'Inicio',
          url: '/home',
          icon: 'home',
          detailTag: 'basicInfo'
        },
        {
          title: 'Deportes',
          url: '/deportes',
          icon: 'american-football',
          detailTag: 'basicInfo'
        },
        {
          title: 'Citas',
          url: '/citas',
          icon: 'bowtie',
          detailTag: 'basicInfo'
        },
        {
          title: 'Bares',
          url: '/bares',
          icon: 'beer',
          detailTag: 'basicInfo'
        },
        {
          title: 'Comida',
          url: '/comida',
          icon: 'pizza',
          detailTag: 'basicInfo'
        },
        {
          title: 'Lugares turisticos',
          url: '/lugares-turisticos',
          icon: 'airplane',
          detailTag: 'basicInfo'
        },
        {
          title: 'Otros',
          url: '/',
          icon: 'disc',
          detailTag: 'basicInfo'
        },
        {
          title: 'Cambiar de cuenta',
          url: '/log-in',
          icon: 'browsers',
          detailTag: 'accountInfo'
        },
        {
          title: 'Configuración',
          url: '/account-config',
          icon: 'build',
          detailTag: 'accountInfo'
        },
        {
          title: 'Salir',
          url: '/',
          icon: 'exit',
          detailTag: 'accountInfo'
        }

      ];

      constructor(){}

    }

例如,在home.page.ts中,我尝试导入它:

代码语言:javascript
复制
    import { AppPages } from '../global_modules/app_pages';

现在,当我导入模块时,我在HomePage类中创建了一个变量,如下所示:

代码语言:javascript
复制
    public appPages;

Home.page.ts的完整代码:

代码语言:javascript
复制
   import { Component } from '@angular/core';
import { BackgroundDirective } from '../../assets/background.directive';/*This directive is needed in each page*/
import { ToastController } from '@ionic/angular';

import { AppPages } from '../../global_modules/app_pages';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})

export class HomePage {

  public gallery_main_route = '../assets/gallery/';
  public appPages;
  public galleryRadioButtons;
  public top_bar_avatar;
  public left_bar_menu_opener;
  public menuCtrl;

  public gallery_images = [

    {
        name: 'sample',
        extension: '.jpg',
        sample_gallery_text: '',
        alt: '',
        checked: 'true'
    },

    {
        name: 'sample2',
        extension: '.jpg',
        sample_gallery_text: '',
        alt: '',
        checked: 'false'
    },

    {
        name: 'sample3',
        extension: '.jpg',
        sample_gallery_text: '',
        alt: '',
        checked: 'false'
    },

    {
        name: 'sample4',
        extension: '.jpg',
        sample_gallery_text: '',
        alt: '',
        checked: 'false'
    },

    {
        name: 'sample5',
        extension: '.png',
        sample_gallery_text: '',
        alt: '',
        checked: 'false'
    }

  ];

  public sample_content = [

    {
        separator_title: 'Restaurantes',
        title: 'Restaurante x',
        src: '../assets/gallery/sample3.jpg',
        description: '¿Un lugar donde comer un platillo exquisito y ademas muy elegante?, suena tentador...',
      loved: 'heart-empty',
      favourite: 'star-outline'
    },
    {
        separator_title: 'Bares',
        title: 'Bar x',
        src: '../assets/gallery/sample4.jpg',
        description: '¿Quieres compartir alguna cerveza con alguien pero no tienes amigos?, con EXTIME, podrás hacerlo!',
      loved: 'heart-empty',
      favourite: 'star-outline'
    },
    {
        separator_title: 'Citas',
        title: 'Cita x',
        src: '../assets/gallery/sample2.jpg',
        description: '¿Eres sociable y deseas conocer y salir con aquellas personas?, EXTIME te da un medio para hacerlo!',
      loved: 'heart-empty',
      favourite: 'star-outline'
    },
    {
        separator_title: 'Lugares turisticos',
        title: 'Lugar turistico x',
        src: '../assets/gallery/sample.jpg',
        description: '¿Que mas placentero que ir de vacaciones a un hermoso lugar?, encuentra los mejores lugares en EXTIME!',
      loved: 'heart-empty',
      favourite: 'star-outline'
    },
    {
        separator_title: 'Lugares deportivos',
        title: 'Lugar deportivo x',
        src: '../assets/gallery/sample5.png',
        description: '¿Disfrutas tambien de hacer ejercicio?, ¡Ningun problema!, aquí en EXTIME, tambien encontraras lugares deportivos de interes personal en los cuales hacer deporte.',
      loved: 'heart-empty',
      favourite: 'star-outline'
    }

  ];

  constructor(public toastController: ToastController){

    this.appPages = AppPages.pages;

  }

  //This function allows you to add any event to an element, and you can attach a callback to that event and pass to it any needed parameters.
  addEvents(element, evType, attachCallback, ...callbackAttributes){

    element.addEventListener(evType, (ev) =>{

      attachCallback(ev, ...callbackAttributes);

    });

  }

  setup(){

    this.appPages = AppPages.pages;
    this.galleryRadioButtons = document.getElementsByClassName('circle_slider_component') as HTMLCollectionOf<HTMLElement>;
    this.top_bar_avatar = document.getElementById('top_right_avatar');
    this.left_bar_menu_opener = document.getElementById("title_component").children[0];
    this.menuCtrl = document.querySelector('ion-menu-controller');

    console.log(this.appPages);

    //Adding menu custom display events.
    this.addEvents(this.top_bar_avatar, "click", this.hideShowMenu, "item-container","accountInfo");
    this.addEvents(this.left_bar_menu_opener, "click", this.hideShowMenu, "item-container", "basicInfo");

  }

  hideShowMenu(ev, elementClassReference,listReference){

    const elements = document.getElementsByClassName(elementClassReference);

    for(let i = 0; i < elements.length; i++){

      if(!(this.appPages[i].detailTag === listReference)){

        elements[i].style.display = "none";

      }else{

        elements[i].style.display = "block";

      }

    }
    this.menuCtrl.open();

  }

  ionViewDidEnter(){

    this.setup();

  }

  async button_toast(message, index){

    switch(message){

      case 'loved':

        if(this.sample_content[index].loved == "heart-empty"){

          this.sample_content[index].loved = "heart";
          const toast = await this.toastController.create({
            message: '¡Haz indicado que te gusta esta pagina!',
            duration: 2000
          });
          return await toast.present();

        }else{

          this.sample_content[index].loved = "heart-empty";
          const toast = await this.toastController.create({
            message: '¡Ya no te gusta esta pagina!',
            duration: 2000
          });
          return await toast.present();

        }

        break;

      case 'favourite':

        if(this.sample_content[index].favourite == "star-outline"){

          this.sample_content[index].favourite = "star";
          const toast = await this.toastController.create({
            message: '¡Haz añadido esta pagina a favoritos!',
            duration: 2000
          });
          return await toast.present();

        }else{

          this.sample_content[index].favourite = "star-outline";
          const toast = await this.toastController.create({
            message: '¡Haz quitado esta pagina de favoritos!',
            duration: 2000
          });
          return await toast.present();

        }

        break;

    }

  }

}

赋值后,当我在setup中console.log变量appPages的值时,我得到了正确的信息(不是未定义的),但当其他函数试图获取该变量的内容时,抛出了这个错误:

core.js:15724错误TypeError:无法在HTMLElement的push../src/app/home/home.page.ts.HomePage.hideShowMenu (home.page.ts:144)读取未定义的属性'appPages‘。(home.page.ts:118)位于ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)位于Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone )的Object.onInvokeTask (core.js:17290)位于ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:422).js:195)在ZoneTask.push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask as invoke at invokeTask (zone.js:1744) at HTMLElement.globalZoneAwareCallback (zone.js:1770)

为什么‘没有赋值’?(考虑到当我console.log变量appPages的内容时,我得到的是正确的信息,而不是未定义的信息)。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-06-26 02:56:21

我解决了!,问题是我试图在页面加载后使用JSON的值(并且我用这个JSON将一些信息加载到HTML中),也就是说!,所以我将赋值改为:

代码语言:javascript
复制
//some stuff...

public appPages;

ionViewWillEnter(){

  this.setup();

}

ionViewDidEnter(){

   /*And here after the page was loaded, i use the functions that requires
    *that value.*/
   this.hideShowMenu();

}

setup(){

  this.appPages = AppPages.pages;

}

但我不知道为什么直接赋值或在构造函数中赋值似乎不起作用。

票数 0
EN

Stack Overflow用户

发布于 2019-06-24 08:31:42

IonViewDidEnter是Ionic的生命周期钩子,在你的主页动画完成后,在经典的初始化钩子(如ngOnInit )之后,它会在“游戏后期”触发。

在赋值之前,您必须调用appPages值。尝试在ngOnInit()钩子或主页构造函数内部运行属性赋值:

代码语言:javascript
复制
constructor() {
    this.appPages = AppPages.pages;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56728201

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档