bringing a variable from a TypeScript file into a different one

I'm facing a challenge with importing a variable from one TypeScript file to another.

The specific variable I need to import is called cityListUrl

The TypeScript file where it's defined looks like this:

export class backendUrls{

  // root url
  rooturl:string= 'http://127.0.0.1:8000';

//get a list of all cities
  cityListUrl:string = this.rooturl + '/api/city/';


}

The file I want to import it into has the following structure:

import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import {backendUrls} from 'app/backendUrls';

@Injectable()
export class cityGetService{
  constructor(private http: Http){}

  cityGet(){
    this.http.get(backendUrls.cityListUrl)
  }
}

When I try to access cityListUrl in my PyCharm editor, it shows up as red with the message:

TS2339: 'cityListUrl' does not exist on type 'typeof backendUrls'.

Has anyone encountered this issue before? Any suggestions on how to resolve it would be greatly appreciated. Thank you

Answer №1

One effective method for managing server api urls is through the utilization of angular environment files. There are two key benefits to using this approach:

  • It is accessible throughout your entire application
  • You can effortlessly handle multiple platforms (localhost, dev, staging, prod) without having to modify your code each time

Within the directory app/environments, you have the ability to create various files:

  • environments.prod.ts
  • environments.ts
  • environment.test.ts

In each file, you define your global variables:

For localhost:

export const environment = {
  production: false,
  apiHost: 'http://localhost',
  recaptchaKey: '6LeWzxQUeazeAAPpR0gZFezaeazL5AvUP3moN1U4u',
  fileHost: 'http://file.localhost',
};

For a production example:

export const environment = {
  production: true,
  apiHost: 'http://prod',
  recaptchaKey: '6LeWzxQUeazeAAPpR0gZFezaeazL5AvUP3moN1U4u',
  fileHost: 'http://file.prod',
};

To utilize these environments in your scripts, simply import

import { environment } from './environments/environment'; //relative path from where your file is

import { environment } from './environments/environment'
export class Service {
    protected cityListUrl = '/api/city/';

    constructor(protected http: Http) { }

    get() {
      this.http.get(environment.apiHost + this.cityListUrl).map(response => response.json());
    }
}

When building your project with angular-cli, specify which environment you wish to use

ng build --environment=prod

or

ng serve --environment=test

This feature is advantageous as it allows for seamless integration of this command line in continuous integration tools.

Answer №2

To simplify, you can individually define and export each variable. This allows for separate imports as well.

export const rooturl = 'http://127.0.0.1:8000';
export const cityListUrl = rooturl + '/api/city/'

When importing:

import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import {cityListUrl} from 'app/backendUrls';

@Injectable()
export class cityGetService{
  constructor(private http: Http){}

  cityGet(){
    this.http.get(cityListUrl)
  }
}

If you prefer to group them in an object:

export const rooturl = 'http://127.0.0.0.1:8000';
export const cityListUrl = rooturl + '/api/city/'

export const all = {
    rooturl, cityListUrl
}

The current setup is a class that needs instantiation to access its properties.

The code generated for the class:

...

// Class instance required for access
this.http.get(new backendUrls().cityListUrl)

...

For static access without instantiation:

export class backendUrls {
    // Static properties for direct access
    static rooturl: string = 'http://127.0.0.1:8000';
    static cityListUrl: string = backendUrls.rooturl + '/api/city/';
}

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

Typescript's Patch<T> type enforces strictness within the codebase

There have been instances where I needed to 'patch' an object T using Object.assign(). For instance, when propagating changes you might modify a stateful object that other code references (common in reactive programming like MobX or Vue). It&ap ...

Switch from Gulp-TSLint to Gulp-ESLint for enhanced code analysis!

I am currently in the process of updating a Gulp task that uses gulp-tslint to now use gulp-eslint. The code snippet below outlines the changes I need to make: const { src } = require('gulp'); const config = require('./config'); const ...

Retrieve the value of a promise and transfer it to the subsequent function of an observable

For my Angular 9 application, I have created a custom interceptor called AuthorizationHeaderInterceptor: @Injectable() export class AuthorizationHeaderInterceptor implements HttpInterceptor { constructor(private authenticationService: AuthenticationSer ...

Tips for generating a subject in rx.js while utilizing 2 parameters

Within my Angular2 application, I am utilizing a communication service to handle interactions between components. When calling the method: this.notification.create('test'); The service structure is as follows: export class NotificationServic ...

leveraging parcel for importing typescript dependencies

I am currently using parcel to process typescript for a web extension. I have installed JQuery and its type definitions via npm. In my typescript file, I have the following at the top: import $ from "jquery"; import "bootstrap"; However, when running run ...

The 'Element[]' type is lacking certain properties when dealing with react children

In my code, there is a parent component passing down its children to a child component. These children can be either single nodes or arrays of nodes, and the ChildComponent renders them differently based on their type. However, when I try to render the Chi ...

Learn how to pass JSON data into an anchor tag with Angular router link and the query parameters attribute set as "<a ... [queryParams]="q=|JSON|

As an Angular user, I am trying to populate a query parameter with a JSON object. <ngx-datatable-column name="Sku" prop="product.sku" [flexGrow]="0.5"> <ng-template let-row="row" let-value="value" ...

Utilizing getServerSideProps and getInitialProps in Next.js to optimize page loading times

My page is not loading when I use getServerSideProps or getInitialProps. It keeps on loading without displaying the content, but everything works fine when I remove them. What could be wrong with my code here? HELP. ... interface Props { data: any; } co ...

What is the best way to include TypeScript definition files in version control?

I am working on a basic asp.net core web application and have integrated javascript libraries using libman. Now, I am looking to incorporate typescript, therefore I have obtained typescript definition files for the libraries via npm. For example: npm ins ...

Having trouble getting the Angular Route to work, any tips on how to fix it?

I am currently learning Angular and have encountered a small issue. When I place the Component in my app.component.html as shown below, it functions correctly: <body> <div class="container"> <app-search-books></app-search-books ...

What is the method for choosing an element by class name in TypeScript?

Currently, I'm working on creating a responsive menu bar that collapses on smaller screens. The challenge I'm facing is that I'm using TypeScript for this project. Is there any guidance on how to translate the following code into TypeScript? ...

Ionic 4 - Best practices for handling asynchronous data with multiple observables

I successfully accessed this route: http://localhost:8100/questions/question?id=3 However, I am facing a challenge in handling two subscribers simultaneously. The first subscriber is responsible for loading the questions array from an external service. ...

Best practices for transferring date objects between a frontend developed in JavaScript/TypeScript and a backend built in ASP.net Core 5

An exciting project I am working on involves a web application with a backend REST web API developed in ASP.net Core 5 and a frontend Angular application written in TypeScript. One of the APIs from the ASP.net backend returns an instance of a C# object de ...

Angular sets the required property only when the button is clicked

Is there a way to make a field required in Angular only when a button is clicked? Currently, the error message appears even before the user interacts with the field. I would like the error message "folder name is required" to only appear when the user cli ...

Error encountered in Angular 6 due to an undefined global variable in browser-crypto.js

Currently, I am working on implementing socketjs and have run into an error. https://i.sstatic.net/VRbDT.png The packages I am using for socket and stomp are listed below: import * as SockJS from 'sockjs-client'; import * as Stomp from 's ...

Error: Module not found - Unable to locate 'dropzone'

Since migrating from Angular 4.4 to Angular 8.0, I encountered the following issue: ERROR in ./src/attributes/import/import.component.ts Module not found: Error: Can't resolve 'dropzone' in 'C:....\src\attributes\imp ...

React Native SectionList Displaying Incorrectly

I have been trying to bind an array of objects to a SelectionList, and although it seems to be binding, each character is being rendered as an individual list item instead of a single item. Take a look at my code snippet: https://i.sstatic.net/Vd6C9.png ...

What is the reason behind webpack attempting to interpret my readme.md files?

When using Webpack, I encountered the errors below. Despite the build appearing to be successful, I am still puzzled as to why these errors are occurring. WARNING in ./{snip}/readme.md Module parse failed: C:{snip}\readme.md Unexpected token (1:7) Y ...

Processing of hierarchical JSON structure

I have a JSON array that I am trying to duplicate only once while keeping it unique. Here is the code I have attempted: return_data = {}; return_data.planner = [{ "date": "2019-08-30T12:10:08.000Z", "event": [{ "name": "Event 1", "col ...

What is the best approach for handling errors in a NestJS service?

const movieData = await this.movieService.getOne(movie_id); if(!movieData){ throw new Error( JSON.stringify({ message:'Error: Movie not found', status:'404' }) ); } const rating = await this.ratingRepository.find( ...