我正在尝试创建一个Ionic应用程序,并使我的代码更加井井有条,我考虑过将其他模块中的某些内容分离并导入,问题是我在分配代码时遇到了“未定义”的问题。静态变量从另一个模块到我要导入的模块。
我试图使导出的模块为静态模块,所以module.ts(我手动完成)如下所示:
<html>
<svg id="plot" viewBox="0 0 100 100" class="chart">
<polyline
id="plotLine"
fill="none"
stroke="#0074d9"
stroke-width="1"
stroke-dasharray=""
stroke-dashoffset="0.00"
points="
00,50
10,70
20,35
30,65
40,77
50,91
"
/>
</svg>
</body>
</html>
/*--------- Menu options---------*/
例如,在home.page.ts中,我尝试将其导入:
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(){}
}
现在,当我导入模块时,我会在 import { AppPages } from '../global_modules/app_pages';
类内创建一个变量,如:
HomePage
home.page.ts的完整代码:
public appPages;
当我在分配后在安装程序中console.log变量appPages的值时,我得到了正确的信息(不是未定义),但是当其他函数试图获取该变量的内容时,抛出此错误:
core.js:15724错误TypeError:无法读取未定义的属性“ appPages” 在推送../src/app/home/home.page.ts.HomePage.hideShowMenu(home.page.ts:144) 在HTMLElement。 (home.page.ts:118) 在ZoneDelegate.push ../ node_modules / zone.js / dist / zone.js.ZoneDelegate.invokeTask(zone.js:423) 在Object.onInvokeTask(core.js:17290) 在ZoneDelegate.push ../ node_modules / zone.js / dist / zone.js.ZoneDelegate.invokeTask(zone.js:422) 在Zone.push ../ node_modules / zone.js / dist / zone.js.Zone.runTask(zone.js:195) 在ZoneTask.push ../ node_modules / zone.js / dist / zone.js.ZoneTask.invokeTask上[作为调用](zone.js:498) 在invokeTask(zone.js:1744) 在HTMLElement.globalZoneAwareCallback(zone.js:1770)
'为什么不分配'?(考虑到当我console.log记录变量appPages的内容时,我得到的是正确的信息,不是未定义的)。
答案 0 :(得分:0)
IonViewDidEnter是Ionic的生命周期挂钩,在为您的首页制作完动画之后以及在像ngOnInit这样的经典初始化挂钩之后,它会在“游戏后期”触发。
在分配appPages值之前,您必须先调用它。尝试在ngOnInit()钩子或Homepage构造函数中运行属性分配:
constructor() {
this.appPages = AppPages.pages;
}
答案 1 :(得分:0)
我解决了!,问题是我试图在页面加载后使用JSON的值(并且我将此JSON的一些信息加载到HTML中),也就是说,所以我将赋值更改为:
//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;
}
但是我不知道为什么直接或在构造函数中的赋值似乎不起作用。