What is the best way to import multiple classes from a module folder in Angular2 using TypeScript?

In my Angular2 application, I have organized my modules as follows:

/app
    /content
        /models
            resource.ts
            container.ts
            entity-type.ts
            index.ts

        /services
            /whatever
                whatever.service.ts

The content of my models index.ts is shown below:

export * from './resource';
export * from './container';
export * from './entity-type';

I am trying to load all the models into whatever.service.ts.

import {Resource, Container} from '../../models';

This is how the barrels loading section in my system-config.js file looks:

const barrels: string[] = [
  // Angular specific barrels.
  '@angular/core',
  '@angular/common',
  '@angular/compiler',
  '@angular/http',
  '@angular/router',
  '@angular/platform-browser',
  '@angular/platform-browser-dynamic',

  // Thirdparty barrels.
  'rxjs',

  // App specific barrels.
  'app',
  'app/shared',
  'app/content',
  /** @cli-barrel */
];

TypeScript compiles without any errors, but when I run it in the browser I encounter issues with certain files not being found by the System loader and Zone.

GET http://localhost:4200/app/content/models.js 404 (Not Found)scheduleTask @ zone.js:101ZoneDelegate.scheduleTask @ zone.js:336Zone.scheduleMacroTask @ zone.js:273(anonymous function) @ zone.js:122send @ VM59771:3fetchTextFromURL @ system.src.js:1154(anonymous function) @ system.src.js:1735ZoneAwarePromise @ zone.js:584(anonymous function) @ system.src.js:1734(anonymous function) @ system.src.js:2759(anonymous function) @ system.src.js:3333(anonymous function) @ system.src.js:3600(anonymous function) @ system.src.js:3985(anonymous function) @ system.src.js:4448(anonymous function) @ system.src.js:4700(anonymous function) @ system.src.js:406ZoneDelegate.invoke @ zone.js:323Zone.run @ zone.js:216(anonymous function) @ zone.js:571ZoneDelegate.invokeTask @ zone.js:356Zone.runTask @ zone.js:256drainMicroTaskQueue @ zone.js:474ZoneTask.invoke @ zone.js:426 zone.js:461 Unhandled Promise rejection: Error: XHR error (404 Not Found) loading http://localhost:4200/app/content/models.js at XMLHttpRequest.wrapFn [as _onreadystatechange] (http://localhost:4200/vendor/zone.js/dist/zone.js:769:30) at ZoneDelegate.invokeTask (http://localhost:4200/vendor/zone.js/dist/zone.js:356:38) at Zone.runTask (http://localhost:4200/vendor/zone.js/dist/zone.js:256:48) at XMLHttpRequest.ZoneTask.invoke (http://localhost:4200/vendor/zone.js/dist/zone.js:423:34) Error loading http://localhost:4200/app/content/models.js as "../../models" from http://localhost:4200/app/content/services/container/container.service.js ; Zone: ; Task: Promise.then ; Value: Error: Error: XHR error (404 Not Found) loading http://localhost:4200/app/content/models.js(…)consoleError @ zone.js:461_loop_1 @ zone.js:490drainMicroTaskQueue @ zone.js:494ZoneTask.invoke @ zone.js:426 zone.js:463 Error: Uncaught (in promise): Error: Error: XHR error (404 Not Found) loading http://localhost:4200/app/content/models.js(…)

When I import each model directly from its respective .ts file, everything works fine.

import { EntityType } from '../../models/entity-type';
import { Container } from '../../models/container';

How can I import modules effectively in Angular2 without encountering these errors?

Answer №1

Based on my understanding, this seems to be the solution you are looking for:

Your ./model/index.ts file should contain the following code:

export * from './resource';
export * from './container';
export * from './entity-type';

Next, if you want to import it into your whatever.service.ts file:

The content of your whatever.service.ts file should be as follows:

import {Resource, Container} from '../models';

By specifying an index file in the models folder, you should be able to simply import the entire folder as demonstrated above.

I hope this clarifies things for you.

Answer №2

Start by creating a new .ts file within the models directory:

Name this new file collective_models.ts:

import * from './entity-type';
import * from './collection';
 ...

After that, you will be able to use the following import statement:

import {Resource, Collection} from '../../models/collective_models';

The main challenge here is making sure to update the all_modules.ts file constantly and include references to any new models in separate .ts files.

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

The mat-datepicker appears in a unique location each time it is opened

I am facing an issue with my mat-datepicker appearing in the opposite place when clicked on one component. How can I resolve this? I have two different components with mat-datepicker, but they behave differently. I suspect that imitating a click in one com ...

Having trouble calling a method from one component to another using its instance

Trying to call a method from one component to another is causing some issues. I have created an instance of the component and tried calling its method, but it doesn't seem to be working as expected. In the code snippet below, you can see that I am try ...

Utilize Firebase to perform a case-insensitive query

Our Angular/Ionic app requires users to provide their email during registration, which is then saved in the User collection. We also validate if the email is already in use with a query like this: firestore .collection("User") .where("email", "==", ...

Designing a versatile Angular component for inputting data (Mailing Address)

Currently, I am in the process of developing an Angular 11 application that requires input for three distinct mailing addresses. Initially, I thought I had a clear understanding of what needed to be done, only to encounter warnings about elements with non- ...

What is the best way to extract Angular's routing UrlMatchResult from UrlMatcher within a component?

Having trouble with routing in Angular 10. Trying to include a token in my URL that can contain various quantities of / characters. To prevent Angular routing from getting confused, I followed the advice on this post and decided to implement the UrlMatcher ...

The system is unable to locate a compatible object with the identifier '[object Object]' of type 'object'. NgFor is limited to binding with iterables like Arrays, not JSON data

Working with JSON data data:[ { assets:[[tool_order_id: "38",order_status_id: "10"]], order_info:[id: "1", order_type: "6",check: "1", current_Stage_id: "29"] }, { assets:[tool_order_ ...

What is the best way to perform type checking for a basic generic function without resorting to using a cumbersome cast

Struggling with TypeScript and trying to understand a specific issue for the past few days. Here is a simplified version: type StrKeyStrVal = { [key: string]: string }; function setKeyVal<T extends StrKeyStrVal>(obj: T, key: keyof T, value: str ...

Angular 8 Refresh Token Implementation

I am currently working on an Angular 8 app that is integrated with .NET Core. My goal is to find a way to refresh a JWT token within the application. Within the integration, users are able to validate and receive a token which expires after 30 minutes. T ...

When implementing JSS with React and TypeScript, certain CSS properties may encounter a `type is unassignable` error

Recently delving into TypeScript, I've encountered an issue within my project that was created using create-react-app with TypeScript and incorporates JSS. It appears that certain CSS properties are causing errors. Specifically, the pointerEvents and ...

What are the best practices for securely storing SSL certificates and public/private keys?

I possess keys that appear like this. MIID0DCCArigAwIBAgIBATANBgkqhkiG9w0BAQUFADB/MQswCQYDVQQGEwJGUjET MBEGA1UECAwKU29tZS1TdGF0ZTEOMAwGA1UEBwwFUGFyaXMxDTALBgNVBAoMBERp bWkxDTALBgNVBAsMBE5TQlUxEDAOBgNVBAMMB0RpbWkgQ0ExGzAZBgkqhkiG9w0B CQEWDGRpbWlAZGltaS5mcjA ...

Adjust the appearance attribute of FormField within the designated theme

Currently, I am collaborating within an NX Monorepo and utilizing a shared ui-components library that extends the capabilities of Angular Material Components. Despite using different themes for various applications, I am aiming to incorporate appearance=&a ...

Understanding the contrast between .value and .setValue within reactive forms in Angular versions 7 and higher

Can you help me distinguish between .value and .setValue in Angular 7+? Under what specific circumstances would it be appropriate to use .value or .setValue? For example, in this scenario: this.createLocForm.setValue(data); And in another case, like this ...

What is the best way to establish anchors for *ngFor elements in Angular 2 and beyond?

I have a component that displays items using *ngFor. My goal is to scroll down to the element with anchor #3. Here's the code snippet: @Component({ selector: 'my-app', template: ` <button (click)="scroll(3)">scroll 2</butt ...

What is the best way to transfer a value from a parent component to a directive within Angular 2?

In the parent component, I currently have this line of code: <input datepicker type="text" (change)="update($event)"/> Is there a way for me to provide a value to the datepicker directive? ...

Is there a way to verify that my transition from angular 2 to angular 4 in my app was successful?

Previously, my .NET WebAPI application utilized angular 2, but I made the decision to transition to angular 4. To upgrade, I executed the following commands in the cmd within my project directory (in addition to addressing any missing dependencies): npm ...

Implementing a class addition on focus event using Angular 2

Currently, I am in the process of upgrading an Angular 1 application to Angular 2 and encountering an issue with one of my existing directives. The task at hand is straightforward. When an input field is focused, a class should be added (md-input-focus) a ...

Exploring TypeScript implementation of Redux toolkit's store

I'm currently diving into the world of Redux in React + TypeScript by following the tutorials provided by Redux Toolkit. I am attempting to implement it in a sample application. My main struggle lies with typings related to the store and the mappStat ...

One important rule to remember when using React Hooks is that they must be called consistently and in the correct order in each render of the component. It

Encountering an issue while trying to use the ternary operator to determine which React Hook to utilize. The error message states: "React Hook "useIsolationDynamicPhase" is called conditionally. React Hooks must be invoked in the same order during every co ...

Encountered a XHR error (404) while attempting to load the script from https://unpkg.com/[email protected]/operators/index.js/first

Struggling with implementing the Google Material input control in angular2, I keep encountering a recurring error in the browser console. https://i.stack.imgur.com/Q5YFA.png: Upon inspecting my 'node_modules' directory, I noticed the presence o ...

Type of event triggered by user file upload via INPUT element

I have a piece of code that reads the contents of a locally stored file. Here is what it looks like: onFile(event: any) { console.log(event); const file = event.target.files[0]; const reader = new FileReader(); reader.onloadend = (ev: any) => { ...