【问题标题】:defining constants in typescript (ionic application)在打字稿中定义常量(离子应用)
【发布时间】:2016-10-18 10:05:18
【问题描述】:

在我的 Ionic 应用程序中,我将常量定义为

//constants.ts
export var CONSTANTS = {
 API_ENDPOINT: 'http://localhost:3000/'
};

并将其导入为

import {CONSTANTS} from '../../services/constants'; //the path is correct

但是我得到错误 CONSTANTS not defined in the file where I importing.. 我在这里缺少什么?

【问题讨论】:

    标签: typescript ionic-framework


    【解决方案1】:

    你应该这样做:

    // constants.ts
    export const API_ENDPOINT= 'http://localhost:3000/';
    

    并将其导入为:

    import * as Constants from '../../services/constants';
    

    你可以这样访问它:

    Constants.API_ENDPOINT;
    

    【讨论】:

    • 如果我想在 constant.ts 中创建多个变量怎么办? 1. 我把它放在项目结构中的什么地方 2. 如何从中访问单个变量 谢谢
    【解决方案2】:

    对于离子

    app.value('config', {
      "constant1": "value1",
      "constant2": "value2"
    });
    

    并通过

    访问它
    config.constant1
    

    不要忘记注入依赖config

    对于 Nativescript

    定义

    var configObject = {
        testData: false,
        apiUrl: "https://www.domain.com/api/v1/"
    };
    

    使用

    var config = require('../../utils/config');
    

    并获得价值

    config.apiUrl
    

    问候

    【讨论】:

    • 我希望您能详细说明添加此代码的位置。在什么文件里面?
    【解决方案3】:

    在我的应用程序中,我在应用程序的主目录中创建了如下所示的常量文件在文件名内部 - “envirionment.ts”

    export const environment = {
      site_url : 'http://localhost/wp',
      quotes_url : '/wp-json/wp/v2/quotes',
      jwt_url: '/wp-json/jwt-auth/v1/token'
    }
    

    然后我从我的提供程序内部导入,如下所示:

    import {environment} from '../../envrionment';
    

    希望对你有帮助,谢谢:)

    【讨论】:

      【解决方案4】:

      但是我得到错误 CONSTANTS not defined 在我正在导入的文件中

      它工作正常。仔细检查:

      • tsconfig.json : 设置了module
      • console.log(CONSTANTS) 在两个文件中查看发生了什么

      【讨论】:

        猜你喜欢
        • 2019-01-23
        • 1970-01-01
        • 2019-01-24
        • 1970-01-01
        • 2016-04-13
        • 2019-04-09
        • 2018-07-25
        • 2015-12-16
        • 1970-01-01
        相关资源
        最近更新 更多