Angular: implementing a service for conditional module imports

Currently, I have a service that is responsible for loading a list of modules:

@Injectable()
export class MyService {

  public allowedModules: any = this.modulesFilter();

  constructor() {
  }

  public modulesFilter() {
    const testPef = true;
    const modulesList= [];
    if (testPef === true) {
      modulesList.push(MyFirstModule);
    } else {
      modulesList.push(MySecondModule);
    }
    return modulesList;
  }
}

Now, in my module file, I attempted to use it like this:

@NgModule({
  imports: [
    CommonModule,
    MyService.allowedModules  // THIS IS WRONG
  ],
  declarations: [],
  providers: [
    MyService
  ],
  exports: [
  ]
})
export class MyModule { }

I acknowledge that accessing the service directly within the module is incorrect.

Any recommendations on how to proceed?

Answer №1

To achieve lazy loading, you can utilize the lazyLoading feature

 export class LoadGuard implements CanLoad {
  constructor(private myService : MyService , private router: Router) {
 }
 canLoad(route: Route): boolean {

  if (this.myService.canBeLoaded()) {
       return true; 
 } else {
    return false;
 }  
} 


{
  path: 'example',
  loadChildren: 'app/example/example.module#ExampleModule',
  canLoad: [LoadGuard]
},

Answer №2

Implementing the canLoad guard in combination with LazyLoading can ensure secure loading of feature modules. Your service will be invoked within the context of canLoad

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

How can I customize the appearance of the file input button in Angular Material?

Despite browsing numerous similar questions, I have yet to find a solution to my issue. My setup includes Angular 11, Angular Material 8, and a file input structured like this: <div class="form-group"> <input #myInput type="fil ...

The inclusion of a custom list preview with prepare in the sanity schema results in errors during the construction

I recently started working with next.js, TypeScript, and Sanity, and everything has been going smoothly so far. I have multiple schemas defined in my project and it works fine in development. The linting checks also do not show any errors. However, when I ...

How can I iterate through JSON data and showcase it on an HTML page?

I am in the process of developing a weather application using The Weather API. So far, I have successfully retrieved the necessary data from the JSON and presented it in HTML format. My next goal is to extract hourly weather information from the JSON and ...

HTML5 Canvas Border

Hey Everyone, I've been working on an HTML5 canvas project where I set the canvas width to $(window).width(). Everything was going smoothly until I added a border, which caused a horizontal scroll to appear. Important: I attempted to use the innerWid ...

Detecting if the request in Yii Framework 2.0 is coming from an AJAX GET call

While utilizing Yii framework 2.0, I have implemented an AJAX GET jQuery script that references a function within a controller class. $.get('localhost/website/index', {param: 'xxxx'}, function(returnedData){ // some code here..... ...

Is there a way to pass a v-modal as an array when setting Axios params?

I am currently dealing with a Vue Multiselect setup where the v-model is an array to accommodate multiple selected options. The challenge I am facing involves calling a route within the loadExtraOptions method and passing the array of IDs as a parameter ...

ngx-translate handling special characters problem

I'm currently working on an angular 4 project where I've implemented ngx-translate. I've encountered an issue with special characters such as à, which are displaying as ?. Do I need to use a specific method to properly translate these spec ...

I need help figuring out how to mention an id using a concatenated variable in the jquery appendTo() method

Using jQuery, I am adding HTML code to a div. One part of this code involves referencing a div's ID by concatenating a variable from a loop. $(... + '<div class="recommendations filter" id="recCards-'+ i +'">' + &apo ...

Is it possible to modify the contents within the JSP div tag without replacing them through an AJAX call?

In my JSP, I face a scenario where there is a div tag with scriptlet content that pulls data from the database every time a request is received from the server. Previously, I was refreshing the entire page with each update, which not only loaded all the re ...

How can real-time data be fetched or connected to Firebase v9 in the onSubmit function?

Please provide the code in firebase-v9 to fetch the onSubmit function from firestore: const onSubmit = (formData) => { console.log(formData) db.collection('emails').add({ to: formData.to, subject: formData.subject, message: formData.mess ...

Tips for defining the operational scope of orbit controls in three.js

I've been working on creating an orientation cube in threeJS and have set up 2 scenes with different viewports, cameras, and controls. Check out the fiddle here var controls = new THREE.OrbitControls( view.camera, container.domElement ); In the fid ...

Authenticating the Gmail API using a specified user ID

Is there a way to manually input email and password for authentication in the Gmail API without using the default Google popup? I need users to enter their login credentials directly, but I can't figure out how to do it. The code I am currently using ...

Invalid Angular form inputs are inoperative but contain valid values

Recently, I created an Angular form featuring two number inputs and a select input. The challenge I've encountered is that even though the model values are being correctly populated in these inputs, the two numbers inputs remain marked as invalid unti ...

Implementing Angular 4 on a Node Express server within Firebase platform

After setting up an angular 4 project using angular cli, I decided to incorporate express into my application. I created a file named app.js with the following content: app.js const express = require('express') const app = express() ...

Effortless login authentication using Disqus through Google or Facebook tokens

I have set up my website to allow users to authenticate through Google and Facebook using passport, which uses the OAuth 2.0 API. Additionally, I am utilizing Disqus to manage the comments system on my site. However, I am running into a problem where user ...

Using Pipe directive in Angular 2 with ES5: Error - Directive annotation missing from constructor

My simple pipe looks like this: app.DisplayKeystrokePipe = ng.core .Pipe({ name: "displayKeystroke" }) .Class({ transform: function() { } }); On the other hand, I have a more complex component/directive: app.Drop ...

What steps should I follow to upgrade my Angular 11 to the newest version while ensuring that all packages and tools are

Upon completing the update and attempting to run the project using ng serve, an error occurred. An uncaught exception was encountered: Module '@angular/compiler-cli/src/tooling' could not be found ...

Ways to pass functions as properties to a React custom modal?

I'm currently working on a React login page setup. The login functionality is embedded in a Modal using the React-Modal library. When a user presses the login button, data is supposed to be sent to a Custom Modal as props to display a notification win ...

How to efficiently pass dynamic props in Next.js persisting layoutuciary

When setting up a persistence layout, I utilize the getLayout function on each page as shown below: import { Layout } from 'hoc'; const Page = () => { return ( <div>hello</div> ); }; Page.getLayout = function getLayout(pa ...

Building a Laravel PHP application that dynamically generates a custom JSON object fetched from the database and passes it from PHP to

I am faced with the task of generating a custom JSON object by organizing data retrieved from PHP in my Controller. I have full control over what information goes where and in what specific order. To accomplish this, it seems like I will need to go throug ...