Encountering issues with utilizing global variables in Ionic 3

Using Ionic 3, I created a class for global variables but encountered an error

Uncaught (in promise): Error: No provider for Globals! Error: No provider for Globals! at injectionError 
(http://localhost:8100/build/vendor.js:1590:86) at noProviderError 

The news.ts file contains the following code:

import {Globals} from "../../app/globals";

constructor(private globals: Globals, public navCtrl: NavController, public navParams: NavParams, private http: Http) {

    this.getData();
}

getData()
{
  this.http.get(this.globals.baseUrl + 'articles').map(res => res.json()).subscribe(data => {
      this.results = data;
      console.log(data)
  });
}

I attempted to import Globals in the app.module within providers but received another error:

Encountered undefined provider! Usually this means you have circular dependencies (might be caused by using 'barrel' index.ts files.

The app.module.ts file imports Globals but does not declare it in providers:

import {NgModule, ErrorHandler} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {IonicApp, IonicModule, IonicErrorHandler} from 'ionic-angular';
import {MyApp} from './app.component';
import {Globals} from 'globals';

import {TabsPage} from '../pages/tabs/tabs';
import {NewsPage} from '../pages/news/news';

import {StatusBar} from '@ionic-native/status-bar';
import {SplashScreen} from '@ionic-native/splash-screen';
import { HttpModule } from '@angular/http';

import {enableProdMode} from '@angular/core';
enableProdMode();

@NgModule({
   declarations: [
    MyApp,
    TabsPage,
    NewsPage
],
imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp),
    HttpModule
],
bootstrap: [IonicApp],
entryComponents: [
    MyApp,
    TabsPage,
    NewsPage
],
providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
]
})
export class AppModule {
}

This is the content of the globals.ts file :

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


@Injectable()
export class Globals {
   baseUrl: string = 'http://127.0.0.1/rest/web/app_dev.php/api/';
   uploadRootDir: string = 'http://localhost/rest/web/';
}

Answer №1

To achieve this, there is no requirement to utilize the provider. Simply create a file named Globals.ts with the following content:

 export class Globals
        {
           static readonly baseUrl: string = 'http://127.0.0.1/rest/web/app_dev.php/api/';
           static readonly uploadRootDir: string = 'http://localhost/rest/web/';
        };

Whenever you need to access it, just import it as demonstrated below.

myPage.ts

import {Globals} from "../../app/globals";

myMethod(){
    console.log(Globals.baseUrl);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorporate a visual element into an Angular Library Component Template using an image asset

Currently, I am working with Angular 10 and aiming to develop a component library that includes images and stylesheets. My main goal is to be able to access these images from the component templates defined in the HTML template. Although I have limited ex ...

Creating a subtype in typescript involves specifying values for certain fields and getting rid of any optional members in the type definition

interface Person{ name:string, age:number, gender?:string } interface Employee extends Person{ name='John Doe', age:number } I am trying to achieve the above structure for a person and employee in TypeScript. I am also curious if something simi ...

Do interfaces in Typescript require nested properties to be mandatory?

My interface contains a nested object: export interface Person { PersonWrapper: { name: string; address: string email?: string; } } When attempting to create an object from this interface, it appears that name is not mandat ...

import error causing an angular application to crash even with the module installed

Is there a possibility that an error is occurring with the import statement even though the syntax is correct and the required library has been installed? Could the issue lie within the core settings files, specifically the ones mentioned below (package.js ...

Exploring Reactive Programming with RxJS and organizing data into individual streams

As I delve deeper into working reactively with Angular 15 and RxJS observables for a UI component, my focus lies on subscribing to data solely within the component template (html). The data is fetched from an external system through a service. However, a c ...

What is the best way to invoke a function in a specific child component from its parent component?

It seems that I might have provided too much information, but the main question remains: how can I call a method in the child component from the parent template's click() event. <button(click)='get()'>GET</button> In my case, th ...

Exploring the potential of TypeScript with native dynamic ES2020 modules, all without the need for Node.js, while also enhancing

I have a TypeScript application that utilizes es16 modules, with most being statically imported. I am now looking to incorporate a (validator) module that is only imported in debug mode. Everything seems to be functioning properly, but I am struggling to f ...

What steps are required to transform a TypeScript class with decorators into a proper Vue component?

When I inquire about the inner workings of vue-class-component, it seems that my question is often deemed too broad. Despite examining the source code, I still struggle to grasp its functionality and feel the need to simplify my understanding. Consider th ...

What is the most efficient way to simultaneously check multiple variables for undefined values?

Before executing my code, I need to ensure that none of the variables in a given list are undefined. In the code snippet below, there are 4 variables with uncertain values. While I can manually check variables a and b to satisfy TypeScript's requirem ...

Transfer a file to Laravel using $request->input()

Is there a way to upload my file to FTP when I'm sending the data from Angular using JSON format instead of using $request->file("Fichier1") in Laravel? Here is an example of how the data is sent from Angular to Laravel: https://i.stack. ...

Issue with Build System CTA's/Callback function functionality not operational

I have encountered an issue with my build/design system. Although everything works fine during development, when I publish my package and try to use the callback function, it does not return the necessary data for me to proceed to the next screen. I tried ...

Navigating to the tsconfig.json file based on the location of the file being linted

In my monorepo, each package currently contains a .eslintrc.cjs file with the following setup: Package-specific ESLint Configuration const path = require('path') const ts = require('typescript') const OFF = 0 const WARN = 1 const ERROR ...

Troubleshooting `TypeError: document.createRange is not a function` error when testing material ui popper using react-testing-library

I am currently working with a material-ui TextField that triggers the opening of a Popper when focused. My challenge now is to test this particular interaction using react-testing-library. Component: import ClickAwayListener from '@material-ui/core/ ...

Centralize all form statuses in a single component, conveniently organized into separate tabs

I am working on a component that consists of 2 tabs, each containing a form: tab1.component.ts : ngOnInit() { this.params = getParameters(); } getParameters() { return { text : 'sample' form: { status: this.f ...

Ways to retrieve the most recent value from an Angular 4 subscription

What is the best way to retrieve the most recent value from a subscribe method in Angular 4? this.AbcSrvice.value.subscribe(data => {console.log(data)}) ...

Discover the power of sharing a service instance in Angular 2 RC5

In the past, I shared a service instance by declaring it as a viewInjectors within my @Component like so: @Component({ selector: 'my-sel', viewInjectors: [SharedService], templateUrl: 'template.html', pipes: [MyPipe] }) ...

invoke a specified function at runtime

I recently came across a useful library called https://github.com/ivanhofer/typesafe-i18n This library has the capability to generate strongly typed translation data and functions, as illustrated below. (the examples provided are simplified for clarity) e ...

Oops! You can't switch to `multiple` mode on a select dropdown once it has already

Here's where the issue lies: This is the code I am referring to: <div fxFlex.gt-lg="100" fxFlex="100" *ngIf="requestAction == 'add'"> <div class="pb-1"> <md2-select plac ...

What is the best way to update properties in a child component using React hooks?

Looking to update the props using react hooks, I came across a method of passing setState function as props to the child component. MainContainer.tsx const MainContainer: React.FC = () => { const [count, setCount] = useState(0); return <Counter ...

Best Practices for Utilizing NPM Modules with TypeScript

I am interested in developing an npm module using TypeScript. Can anyone suggest a best practice guide on how to start? Here are my questions: Node.js does not natively support TypeScript, so what is the recommended way to publish an npm module? Shoul ...