How to use Dependency Injection in Angular 6 export function

Multi tool use
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
add a comment |
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
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
add a comment |
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
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
angular
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
add a comment |
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
add a comment |
2 Answers
2
active
oldest
votes
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)]
})
}
}
add a comment |
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
})
)
}
}
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
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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)]
})
}
}
add a comment |
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)]
})
}
}
add a comment |
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)]
})
}
}
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)]
})
}
}
answered Nov 26 '18 at 17:40


JohnJohn
2,8471330
2,8471330
add a comment |
add a comment |
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
})
)
}
}
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
add a comment |
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
})
)
}
}
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
add a comment |
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
})
)
}
}
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
})
)
}
}
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
add a comment |
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
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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