How to use Dependency Injection in Angular 6 export function

Multi tool use
Multi tool use












0















I have tried this



export function uniqueUserNameValidation(commonsService: CommonsService): AsyncValidatorFn {
return (c: AbstractControl): Promise < ValidationErrors | null > | Observable < ValidationErrors | null > => {
return commonsService.uniqueUserName(c.value).pipe(
map(data => {
return data && data.status ? {
'uniqueValidation': true
} : null
})
)
}
}


Common Services Method



uniqueUserName(name:string){
return this.http.get<booleanData>(constDefault.API_URL+"/commons/nameAlreadyExist/"+name+"/Tank")
}


I am getting this error




core.js:1673 ERROR Error: Uncaught (in promise): TypeError: Cannot
read property 'uniqueUserName' of undefined
TypeError: Cannot read property 'uniqueUserName' of undefined











share|improve this question

























  • You can't. Just write a regular service with a method that returns an AsyncValidatorFn. Or write that function directly in the component which needs it, and inject the service in the component.

    – JB Nizet
    Nov 26 '18 at 10:43











  • @holydragon no. It's because the commonsService variable is undefined: Cannot read property 'uniqueUserName' of undefined.

    – JB Nizet
    Nov 26 '18 at 10:52
















0















I have tried this



export function uniqueUserNameValidation(commonsService: CommonsService): AsyncValidatorFn {
return (c: AbstractControl): Promise < ValidationErrors | null > | Observable < ValidationErrors | null > => {
return commonsService.uniqueUserName(c.value).pipe(
map(data => {
return data && data.status ? {
'uniqueValidation': true
} : null
})
)
}
}


Common Services Method



uniqueUserName(name:string){
return this.http.get<booleanData>(constDefault.API_URL+"/commons/nameAlreadyExist/"+name+"/Tank")
}


I am getting this error




core.js:1673 ERROR Error: Uncaught (in promise): TypeError: Cannot
read property 'uniqueUserName' of undefined
TypeError: Cannot read property 'uniqueUserName' of undefined











share|improve this question

























  • You can't. Just write a regular service with a method that returns an AsyncValidatorFn. Or write that function directly in the component which needs it, and inject the service in the component.

    – JB Nizet
    Nov 26 '18 at 10:43











  • @holydragon no. It's because the commonsService variable is undefined: Cannot read property 'uniqueUserName' of undefined.

    – JB Nizet
    Nov 26 '18 at 10:52














0












0








0








I have tried this



export function uniqueUserNameValidation(commonsService: CommonsService): AsyncValidatorFn {
return (c: AbstractControl): Promise < ValidationErrors | null > | Observable < ValidationErrors | null > => {
return commonsService.uniqueUserName(c.value).pipe(
map(data => {
return data && data.status ? {
'uniqueValidation': true
} : null
})
)
}
}


Common Services Method



uniqueUserName(name:string){
return this.http.get<booleanData>(constDefault.API_URL+"/commons/nameAlreadyExist/"+name+"/Tank")
}


I am getting this error




core.js:1673 ERROR Error: Uncaught (in promise): TypeError: Cannot
read property 'uniqueUserName' of undefined
TypeError: Cannot read property 'uniqueUserName' of undefined











share|improve this question
















I have tried this



export function uniqueUserNameValidation(commonsService: CommonsService): AsyncValidatorFn {
return (c: AbstractControl): Promise < ValidationErrors | null > | Observable < ValidationErrors | null > => {
return commonsService.uniqueUserName(c.value).pipe(
map(data => {
return data && data.status ? {
'uniqueValidation': true
} : null
})
)
}
}


Common Services Method



uniqueUserName(name:string){
return this.http.get<booleanData>(constDefault.API_URL+"/commons/nameAlreadyExist/"+name+"/Tank")
}


I am getting this error




core.js:1673 ERROR Error: Uncaught (in promise): TypeError: Cannot
read property 'uniqueUserName' of undefined
TypeError: Cannot read property 'uniqueUserName' of undefined








angular






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 26 '18 at 10:56









Samuel J Mathew

3,62212229




3,62212229










asked Nov 26 '18 at 10:39









Roshan BagdeRoshan Bagde

276




276













  • You can't. Just write a regular service with a method that returns an AsyncValidatorFn. Or write that function directly in the component which needs it, and inject the service in the component.

    – JB Nizet
    Nov 26 '18 at 10:43











  • @holydragon no. It's because the commonsService variable is undefined: Cannot read property 'uniqueUserName' of undefined.

    – JB Nizet
    Nov 26 '18 at 10:52



















  • You can't. Just write a regular service with a method that returns an AsyncValidatorFn. Or write that function directly in the component which needs it, and inject the service in the component.

    – JB Nizet
    Nov 26 '18 at 10:43











  • @holydragon no. It's because the commonsService variable is undefined: Cannot read property 'uniqueUserName' of undefined.

    – JB Nizet
    Nov 26 '18 at 10:52

















You can't. Just write a regular service with a method that returns an AsyncValidatorFn. Or write that function directly in the component which needs it, and inject the service in the component.

– JB Nizet
Nov 26 '18 at 10:43





You can't. Just write a regular service with a method that returns an AsyncValidatorFn. Or write that function directly in the component which needs it, and inject the service in the component.

– JB Nizet
Nov 26 '18 at 10:43













@holydragon no. It's because the commonsService variable is undefined: Cannot read property 'uniqueUserName' of undefined.

– JB Nizet
Nov 26 '18 at 10:52





@holydragon no. It's because the commonsService variable is undefined: Cannot read property 'uniqueUserName' of undefined.

– JB Nizet
Nov 26 '18 at 10:52












2 Answers
2






active

oldest

votes


















1














Angular's automatic dependency injection only works for angular component constructors (which are being managed by the DI system).



As a solution to the specific problem shown in the question, you can inject the service into the component which will be calling the uniqueUserNameValidation and then pass the service as an argument to uniqueUserNameValidation. I think that, in general, this would be the preferred solution to your problem because it doesn't stray from standard angular practices.



Example



export class MyComponent {
constructor(private commonsService: CommonsService, private fb: FormBuilder) {}

ngOnInit() {
const form = this.fb.group({
name: ['', uniqueUserNameValidation(this.commonsService)]
})
}
}





share|improve this answer































    0














    I assume that your CommonsService is a proper Angular Service. If so, you could use Injector.



    First import and declare the Injector in your module (app.module.ts etc.) and in the constructor of module init the instance:



    import {Injector} from '@angular/core';

    export let InjectorInstance: Injector;

    ...
    ...
    ...


    export class AppModule {

    constructor(private injector: Injector) {
    InjectorInstance = this.injector;
    }
    }


    Then in your file that is exporting the function, import the variable from the module:



    import {InjectorInstance} from 'path/to/app.module';


    Then you can use the .get() method of Injector to get the service instance:



    export function uniqueUserNameValidation(): AsyncValidatorFn {

    const commonsService = InjectorInstance.get<CommonsService>(CommonsService);

    return (c: AbstractControl): Promise < ValidationErrors | null > | Observable < ValidationErrors | null > => {
    return commonsService.uniqueUserName(c.value).pipe(
    map(data => {
    return data && data.status ? {
    'uniqueValidation': true
    } : null
    })
    )
    }
    }





    share|improve this answer


























    • Now I am getting this error: TypeError: Cannot read property 'get' of undefined

      – Roshan Bagde
      Nov 26 '18 at 13:36













    • It's my bad. I forgot to add init code in the constructor. Edited the answer.

      – Harun Yılmaz
      Nov 26 '18 at 14:23











    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53479324%2fhow-to-use-dependency-injection-in-angular-6-export-function%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    Angular's automatic dependency injection only works for angular component constructors (which are being managed by the DI system).



    As a solution to the specific problem shown in the question, you can inject the service into the component which will be calling the uniqueUserNameValidation and then pass the service as an argument to uniqueUserNameValidation. I think that, in general, this would be the preferred solution to your problem because it doesn't stray from standard angular practices.



    Example



    export class MyComponent {
    constructor(private commonsService: CommonsService, private fb: FormBuilder) {}

    ngOnInit() {
    const form = this.fb.group({
    name: ['', uniqueUserNameValidation(this.commonsService)]
    })
    }
    }





    share|improve this answer




























      1














      Angular's automatic dependency injection only works for angular component constructors (which are being managed by the DI system).



      As a solution to the specific problem shown in the question, you can inject the service into the component which will be calling the uniqueUserNameValidation and then pass the service as an argument to uniqueUserNameValidation. I think that, in general, this would be the preferred solution to your problem because it doesn't stray from standard angular practices.



      Example



      export class MyComponent {
      constructor(private commonsService: CommonsService, private fb: FormBuilder) {}

      ngOnInit() {
      const form = this.fb.group({
      name: ['', uniqueUserNameValidation(this.commonsService)]
      })
      }
      }





      share|improve this answer


























        1












        1








        1







        Angular's automatic dependency injection only works for angular component constructors (which are being managed by the DI system).



        As a solution to the specific problem shown in the question, you can inject the service into the component which will be calling the uniqueUserNameValidation and then pass the service as an argument to uniqueUserNameValidation. I think that, in general, this would be the preferred solution to your problem because it doesn't stray from standard angular practices.



        Example



        export class MyComponent {
        constructor(private commonsService: CommonsService, private fb: FormBuilder) {}

        ngOnInit() {
        const form = this.fb.group({
        name: ['', uniqueUserNameValidation(this.commonsService)]
        })
        }
        }





        share|improve this answer













        Angular's automatic dependency injection only works for angular component constructors (which are being managed by the DI system).



        As a solution to the specific problem shown in the question, you can inject the service into the component which will be calling the uniqueUserNameValidation and then pass the service as an argument to uniqueUserNameValidation. I think that, in general, this would be the preferred solution to your problem because it doesn't stray from standard angular practices.



        Example



        export class MyComponent {
        constructor(private commonsService: CommonsService, private fb: FormBuilder) {}

        ngOnInit() {
        const form = this.fb.group({
        name: ['', uniqueUserNameValidation(this.commonsService)]
        })
        }
        }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 26 '18 at 17:40









        JohnJohn

        2,8471330




        2,8471330

























            0














            I assume that your CommonsService is a proper Angular Service. If so, you could use Injector.



            First import and declare the Injector in your module (app.module.ts etc.) and in the constructor of module init the instance:



            import {Injector} from '@angular/core';

            export let InjectorInstance: Injector;

            ...
            ...
            ...


            export class AppModule {

            constructor(private injector: Injector) {
            InjectorInstance = this.injector;
            }
            }


            Then in your file that is exporting the function, import the variable from the module:



            import {InjectorInstance} from 'path/to/app.module';


            Then you can use the .get() method of Injector to get the service instance:



            export function uniqueUserNameValidation(): AsyncValidatorFn {

            const commonsService = InjectorInstance.get<CommonsService>(CommonsService);

            return (c: AbstractControl): Promise < ValidationErrors | null > | Observable < ValidationErrors | null > => {
            return commonsService.uniqueUserName(c.value).pipe(
            map(data => {
            return data && data.status ? {
            'uniqueValidation': true
            } : null
            })
            )
            }
            }





            share|improve this answer


























            • Now I am getting this error: TypeError: Cannot read property 'get' of undefined

              – Roshan Bagde
              Nov 26 '18 at 13:36













            • It's my bad. I forgot to add init code in the constructor. Edited the answer.

              – Harun Yılmaz
              Nov 26 '18 at 14:23
















            0














            I assume that your CommonsService is a proper Angular Service. If so, you could use Injector.



            First import and declare the Injector in your module (app.module.ts etc.) and in the constructor of module init the instance:



            import {Injector} from '@angular/core';

            export let InjectorInstance: Injector;

            ...
            ...
            ...


            export class AppModule {

            constructor(private injector: Injector) {
            InjectorInstance = this.injector;
            }
            }


            Then in your file that is exporting the function, import the variable from the module:



            import {InjectorInstance} from 'path/to/app.module';


            Then you can use the .get() method of Injector to get the service instance:



            export function uniqueUserNameValidation(): AsyncValidatorFn {

            const commonsService = InjectorInstance.get<CommonsService>(CommonsService);

            return (c: AbstractControl): Promise < ValidationErrors | null > | Observable < ValidationErrors | null > => {
            return commonsService.uniqueUserName(c.value).pipe(
            map(data => {
            return data && data.status ? {
            'uniqueValidation': true
            } : null
            })
            )
            }
            }





            share|improve this answer


























            • Now I am getting this error: TypeError: Cannot read property 'get' of undefined

              – Roshan Bagde
              Nov 26 '18 at 13:36













            • It's my bad. I forgot to add init code in the constructor. Edited the answer.

              – Harun Yılmaz
              Nov 26 '18 at 14:23














            0












            0








            0







            I assume that your CommonsService is a proper Angular Service. If so, you could use Injector.



            First import and declare the Injector in your module (app.module.ts etc.) and in the constructor of module init the instance:



            import {Injector} from '@angular/core';

            export let InjectorInstance: Injector;

            ...
            ...
            ...


            export class AppModule {

            constructor(private injector: Injector) {
            InjectorInstance = this.injector;
            }
            }


            Then in your file that is exporting the function, import the variable from the module:



            import {InjectorInstance} from 'path/to/app.module';


            Then you can use the .get() method of Injector to get the service instance:



            export function uniqueUserNameValidation(): AsyncValidatorFn {

            const commonsService = InjectorInstance.get<CommonsService>(CommonsService);

            return (c: AbstractControl): Promise < ValidationErrors | null > | Observable < ValidationErrors | null > => {
            return commonsService.uniqueUserName(c.value).pipe(
            map(data => {
            return data && data.status ? {
            'uniqueValidation': true
            } : null
            })
            )
            }
            }





            share|improve this answer















            I assume that your CommonsService is a proper Angular Service. If so, you could use Injector.



            First import and declare the Injector in your module (app.module.ts etc.) and in the constructor of module init the instance:



            import {Injector} from '@angular/core';

            export let InjectorInstance: Injector;

            ...
            ...
            ...


            export class AppModule {

            constructor(private injector: Injector) {
            InjectorInstance = this.injector;
            }
            }


            Then in your file that is exporting the function, import the variable from the module:



            import {InjectorInstance} from 'path/to/app.module';


            Then you can use the .get() method of Injector to get the service instance:



            export function uniqueUserNameValidation(): AsyncValidatorFn {

            const commonsService = InjectorInstance.get<CommonsService>(CommonsService);

            return (c: AbstractControl): Promise < ValidationErrors | null > | Observable < ValidationErrors | null > => {
            return commonsService.uniqueUserName(c.value).pipe(
            map(data => {
            return data && data.status ? {
            'uniqueValidation': true
            } : null
            })
            )
            }
            }






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 26 '18 at 14:22

























            answered Nov 26 '18 at 11:16









            Harun YılmazHarun Yılmaz

            874717




            874717













            • Now I am getting this error: TypeError: Cannot read property 'get' of undefined

              – Roshan Bagde
              Nov 26 '18 at 13:36













            • It's my bad. I forgot to add init code in the constructor. Edited the answer.

              – Harun Yılmaz
              Nov 26 '18 at 14:23



















            • Now I am getting this error: TypeError: Cannot read property 'get' of undefined

              – Roshan Bagde
              Nov 26 '18 at 13:36













            • It's my bad. I forgot to add init code in the constructor. Edited the answer.

              – Harun Yılmaz
              Nov 26 '18 at 14:23

















            Now I am getting this error: TypeError: Cannot read property 'get' of undefined

            – Roshan Bagde
            Nov 26 '18 at 13:36







            Now I am getting this error: TypeError: Cannot read property 'get' of undefined

            – Roshan Bagde
            Nov 26 '18 at 13:36















            It's my bad. I forgot to add init code in the constructor. Edited the answer.

            – Harun Yılmaz
            Nov 26 '18 at 14:23





            It's my bad. I forgot to add init code in the constructor. Edited the answer.

            – Harun Yılmaz
            Nov 26 '18 at 14:23


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53479324%2fhow-to-use-dependency-injection-in-angular-6-export-function%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            bsF,o8KeGMO P8T1wE,OhA,Xes ZfvbOcW80ef5n1OvAtj47DSVQK4Wm elEQ,5iIBA6Tc3
            hfJqPeBljipqa4h ESfB6,B8S,LMwcDfr617 R,o1KAp,KhLVzJ6c u

            Popular posts from this blog

            A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

            Calculate evaluation metrics using cross_val_predict sklearn

            Command to identify the expired API token and generates the new token in shell