Angular 4: how to pass an argument to the service provided in the module file

I am asking you for help on which method to use here: I checked a lot of things to solve my problem and I have at least 4 working solutions, but I don’t know which ones will be better, and if some of them only work because of the side effect of something else that I did and should not be used ...

I could not find anything in the documentation to point me to one of these solutions (or another)

Firstly, here is my situation . I am creating an application that connects to the data API and creates different sections, each of which contains dataviz.

I built the sections of the site as modules, but they share a service called DataService (each of these modules will use a DataService to receive and process data).

My DataService needs a configuration file with several parameters that apply to each section and are stored in its own folder.

Therefore, I need to provide a DataService separately for each section, in the suppliers section of the module.ts file, and it would be good practice to avoid copying the DataService into each module ...

Thus, the file architecture will be:

--Dashboard module
----data.service.ts
----Section1 module
------Section1 config file
----Section2 module
------Section2 config file

I tried several things that seem to work in the section module file:

Solution 1: injection

(I could not get the injection to work without quotes, even if I hadn’t seen anything)

Module File:

import { DataService } from '../services/data.service';
import viewConfig from './view.config.json';

@NgModule({
    imports: [ ... ],
    declarations: [ ... ],
    providers: [
        { provide: 'VIEW_CONFIG', useValue: viewConfig },
        DataService,
    ]})
   export class Section1Module { }

Section File:

@Injectable()
export class DataService {

    constructor(@Inject('VIEW_CONFIG') private viewConfig : any) {}

}

Solution 2: factory supplier

Doesn't work after rebooting ng (see update)

< > https://angular.io/docs/ts/latest/guide/dependency-injection.html#!#factory-provider

:

import { DataService } from '../services/data.service';
import viewConfig from './view.config.json';

export let VIEW_CONFIG = new InjectionToken<any>('');
let dataServiceFactory = (configObject):DataService => {
    return new DataService(configObject)
}

@NgModule({
    imports: [ ... ],
    declarations: [ ... ],
    providers: [
        { provide: VIEW_CONFIG, useValue: viewConfig },
        {
            provide : DataService,
            useFactory : dataServiceFactory,
            deps : [VIEW_CONFIG]
        },
    ]})
   export class Section1Module { }

:

@Injectable()
export class DataService {

    constructor(private viewConfig : any) {}

}

3: instanciation >

ng (. )

< > :

import { DataService } from '../services/data.service';
import viewConfig from './view.config.json';

@NgModule({
    imports: [ ... ],
    declarations: [ ... ],
    providers: [
        { provide: DataService, useValue : new DataService(viewConfig) },
    ]})
   export class Section1Module { }

:

@Injectable()
export class DataService {

    constructor(private viewConfig : any) {}

}

4. factory >

ng (. )

< > 3...

:

import { DataService } from '../services/data.service';
import viewConfig from './view.config.json';

let dataServiceFactory = (configObject) => { return new DataService(configObject) }

@NgModule({
    imports: [ ... ],
    declarations: [ ... ],
    providers: [
         { provide: DataService, useValue : dataServiceFactory(viewConfig) }
    ]})
   export class Section1Module { }

:

@Injectable()
export class DataService {

    constructor(private viewConfig : any) {}

}

5 factory, AND

:

export const VIEW_CONFIG = new InjectionToken<any>('');

 @NgModule({
    imports: [ ... ],
    declarations: [ ... ],
    providers: [
         { provide: VIEW_CONFIG, useValue: viewConfig },
         { provide : DataService,
           useFactory: dataServiceFactory,
           deps : [VIEW_CONFIG] }
    ]})
   export class Section1Module { }

:

@Injectable()
export class DataService {
    constructor(private viewConfig : any) {}
}

export function dataServiceFactory(configObject) {
    return new DataService(configObject);
}

, , : " ?" " ?"

!: D


UPDATE - , Angular -CLI , , "ng serve". , CLI , , CLI, ...

1:

2/ 3: :

Error encountered resolving symbol values statically. Calling function 
'DataService', function calls are not supported. Consider replacing the 
function or lambda with a reference to an exported function

4: :

Error encountered resolving symbol values statically. Reference to a non-exported function

5

+4
1

:

:

export const IBO_DETAILS_GENERAL = {
    iboCode: 'IBOsFormCodeField',
    iboGivenName: 'IBOsFormGivenNameField',
    iboFamilyName: 'IBOsFormFamilyNameField',
    iboEmail: 'IBOsFormEmailField',
};

export const IBO_DETAILS_ACCOUNT = [];

:

import { IBO_DETAILS_GENERAL } from './ibo-details-formfields';

@Component({
    selector: 'ibo-details-general',
    templateUrl: './ibo-details-general.component.html',
    styles: [],
})
export class IboDetailsGeneral extends FilterDataMappingManipulator implements OnInit, OnDestroy {
    // Initial constants,vectors and component mapping
    private formFields = IBO_DETAILS_GENERAL;

, , config formFields. .

(, ..) , API.

(formFields ), , , .

, . , . providers , . :

@NgModule({
    declarations: [
        ChildComp1,
        ChildComp2
    ],
    imports: [
    ],
    providers: [
        SharedService
    ]
})
export class SectionModule {
}

, ChildComp1 ChildComp2 SharedService, .

, , , User. , , UsersModule providers UsersSharedService, declarations UsersLeftPanel UsersRightPanel ().

1:

.

, :

getData() {
  // do Stuff
  let myData = {}; // Result of the stuff we did
  this.dataSubject.next(myData);
}

:

this.myService.getData();

Right?

, , ? .

this.myService.getData(this.formFields);

, :

   getData(currentConfig) {
      // do Stuff depending on currentConfig obj received as parameter
      let myData = {}; // Result of the stuff we did
      this.dataSubject.next(myData);
    }

getData() , . , providers, / , , , .

2:

5, , multi: true.

:

export function dataServiceFactory(configObject) {
    return () => new DataService(configObject);
}

providers: [
     { provide: VIEW_CONFIG, useValue: viewConfig },
     { provide : DataService,
       useFactory: dataServiceFactory,
       deps : [VIEW_CONFIG],
       multi: true }
]})

return : return () =>.

:

export function initConfigFactory(userConfig: UserConfig) {
    return () => userConfig.getUsersConfig();
}

userConfig.getUsersConfig() - , .

providers: [
    {
        provide: APP_INITIALIZER,
        useFactory: initConfigFactory,
        deps: [UserConfig],
        multi: true
    }
]

5, !

+1

Source: https://habr.com/ru/post/1676133/


All Articles