Issue
I have a Angular App with main-component AppComponent that uses a module MyMod that needs config information at start.
I also have a service MyServ that provides these information.
app.module.ts
@NgModule({
declarations: [
AppComponent
],
imports: [
MyMod.forRoot ({
param: "12345" // the parameter!
})
],
providers: [MyServ],
bootstrap: [AppComponent]
})
myserv.service.ts
@Injectable ()
export class MyServ
{
getParam () : string
{
return "12345";
}
}
Is it possible I can use myserv.getParam () in app.modules.ts to init MyMod??
Solution
You need to define the method as static, to access directly, please find below a working example!
ts
import { Component, Inject } from '@angular/core';
import 'zone.js';
import { SOME_STRING } from './test/test.module';
@Component({
selector: 'app-root',
template: `
<h1>Hello from {{ name }}!</h1>
<a target="_blank" href="https://angular.dev/overview">
Learn more about Angular
</a>
`,
})
export class AppComponent {
name = 'Angular';
constructor(@Inject(SOME_STRING) private someString: string) {
this.name = someString;
}
}
app.module
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { TestModule } from './test/test.module';
import { TestService } from './test.service';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({
imports: [
CommonModule,
ReactiveFormsModule,
BrowserModule,
TestModule.forRoot({
param: TestService.getParam(), // the parameter!
}),
],
providers: [TestService],
declarations: [AppComponent],
bootstrap: [AppComponent],
})
export class AppModule {}
service
import { Injectable } from '@angular/core';
@Injectable()
export class TestService {
constructor() {}
static getParam(): string {
return '12345';
}
}
Answered By - Naren Murali
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.