how to create a constant file in the ionic 3?

2020-05-01 05:40发布

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

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' } ];

2条回答
萌系小妹纸
2楼-- · 2020-05-01 05:48

Very Simple! Just follow these two steps -

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

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

So, your app.constants.ts would be like -

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' } 
    ];
}

And, use it as -

// 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);
    }
}
查看更多
虎瘦雄心在
3楼-- · 2020-05-01 05:56
登录 后发表回答