如何在ionic 3中创建一个常量文件? [英] how to create a constant file in the ionic 3?

查看:137
本文介绍了如何在ionic 3中创建一个常量文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

设置/设置要在整个应用中使用的全局常量(例如API URL字符串)的最佳/推荐方法是什么?

What is the best/recommended way to set a global constant to be used across the entire app, like an API URL string?

我具有JSON格式,并希望设置一个全局常量,并在整个应用程序中将其用作静态. import { Injectable } from '@angular/core';

I have the JSON format and want to set a global constant and use across the entire app as a static. import { Injectable } from '@angular/core';

@Injectable() export class Service { item_data = [ { item_id:'1', item_image: "assets/img/bluesaphire.jpg", item_title:'Blue Saphire Stone' } ];

推荐答案

非常简单!只需遵循以下两个步骤-

Very Simple! Just follow these two steps -

1)创建一个 可注入 类(例如AppConstants)

1) Create an Injectable class (eg. AppConstants) in a root directory (eg. src) with required properties

2)将其导入您的组件类构造函数&中.在需要的地方使用

2) Import it in your component class constructor & use wherever needed

因此,您的 app.constants.ts 就像-

import { Injectable } from '@angular/core';

@Injectable({
    providedIn: 'root'
})
public class AppConstants {
    public item_data = [
        { item_id:'1', item_image: "assets/img/bluesaphire.jpg",  item_title:'Blue Saphire Stone' } 
    ];
}

然后,将其用作-

// here, config is a directory & app.constants is a ts file
import { AppConstants } from '../../config/app.constants';    // update your way

public class TestComponent {
    // dependency injection
    constructor(private constants: AppConstants) { }

    testMethod() {
        // using it here
        console.log(this.constants.item_data);
    }
}

这篇关于如何在ionic 3中创建一个常量文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆