use of this in constructor in refrence with dependencies injection in angular
I was checking Angular Official documents and other blogs and see 2 different kinds of syntax for DI when using within the constructor, sometimes they use this and sometimes no use of this. which one is correct?
I know we need to use this in any other method of the class but why we do not use this in the constructor. or just private and public identifier makes the difference to use of this
import { Component } from '@angular/core';
class NameService {
getName () {
return "Angular";
}
}
@Component({
selector: 'my-app',
template: '<h1>Favourite framework: {{ name }}</h1>'
})
class AppComponent {
name: string;
constructor(nameService: NameService) {
this.name = nameService.getName(); // do not use this
}
otherMethod() {
this.nameService.getName(); // use this
}
}
somewhere I have seen people using this within the constructor. here one of the example
constructor(@Optional() private logger: Logger) {
if (this.logger) {
this.logger.log(some_message); // using this
}
}
so when do we use this and when not? or we are using this in later example because of @Optional decorators?
add a comment |
I was checking Angular Official documents and other blogs and see 2 different kinds of syntax for DI when using within the constructor, sometimes they use this and sometimes no use of this. which one is correct?
I know we need to use this in any other method of the class but why we do not use this in the constructor. or just private and public identifier makes the difference to use of this
import { Component } from '@angular/core';
class NameService {
getName () {
return "Angular";
}
}
@Component({
selector: 'my-app',
template: '<h1>Favourite framework: {{ name }}</h1>'
})
class AppComponent {
name: string;
constructor(nameService: NameService) {
this.name = nameService.getName(); // do not use this
}
otherMethod() {
this.nameService.getName(); // use this
}
}
somewhere I have seen people using this within the constructor. here one of the example
constructor(@Optional() private logger: Logger) {
if (this.logger) {
this.logger.log(some_message); // using this
}
}
so when do we use this and when not? or we are using this in later example because of @Optional decorators?
add a comment |
I was checking Angular Official documents and other blogs and see 2 different kinds of syntax for DI when using within the constructor, sometimes they use this and sometimes no use of this. which one is correct?
I know we need to use this in any other method of the class but why we do not use this in the constructor. or just private and public identifier makes the difference to use of this
import { Component } from '@angular/core';
class NameService {
getName () {
return "Angular";
}
}
@Component({
selector: 'my-app',
template: '<h1>Favourite framework: {{ name }}</h1>'
})
class AppComponent {
name: string;
constructor(nameService: NameService) {
this.name = nameService.getName(); // do not use this
}
otherMethod() {
this.nameService.getName(); // use this
}
}
somewhere I have seen people using this within the constructor. here one of the example
constructor(@Optional() private logger: Logger) {
if (this.logger) {
this.logger.log(some_message); // using this
}
}
so when do we use this and when not? or we are using this in later example because of @Optional decorators?
I was checking Angular Official documents and other blogs and see 2 different kinds of syntax for DI when using within the constructor, sometimes they use this and sometimes no use of this. which one is correct?
I know we need to use this in any other method of the class but why we do not use this in the constructor. or just private and public identifier makes the difference to use of this
import { Component } from '@angular/core';
class NameService {
getName () {
return "Angular";
}
}
@Component({
selector: 'my-app',
template: '<h1>Favourite framework: {{ name }}</h1>'
})
class AppComponent {
name: string;
constructor(nameService: NameService) {
this.name = nameService.getName(); // do not use this
}
otherMethod() {
this.nameService.getName(); // use this
}
}
somewhere I have seen people using this within the constructor. here one of the example
constructor(@Optional() private logger: Logger) {
if (this.logger) {
this.logger.log(some_message); // using this
}
}
so when do we use this and when not? or we are using this in later example because of @Optional decorators?
edited Nov 23 '18 at 6:07
Bunyamin Coskuner
4,06211036
4,06211036
asked Nov 23 '18 at 5:49
diEchodiEcho
38k27129202
38k27129202
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
It is all about Typescript. When you use public, private or protected on a constructor parameters as follows
constructor(private logger: Logger) {}
In reality, Typescript creates a field with the same name and set it for you.
So, instead of writing following code you could simply write the code above
private logger: Logger;
constructor(logger: Logger) {
this.logger = logger;
}
Since, you already wrote private logger, you can simply use your field with this. It does not really matter how you use it within constructor.
There is a Typescript Playground where you can try this out and see it yourself. Whatever you type in the left box will be converted into plain JS (ES5) in the right box.
@Optional decorator just tells Angular that it is OK if it cannot find that object to inject.
Rule of thumb:
If you use private, protected or public on a any field and want to use it, always use this (within constructor)
If you didn’t mark the field with any of the keywords above, you cannot use this and cannot access that object outside of constructor.
If you need to access a property/method of a class, you HAVE to use this.
Thanks for the explanation but still confused whether to usethisor not within the constructor?
– diEcho
Nov 23 '18 at 6:15
I edited my answer, check it out @diEcho
– Bunyamin Coskuner
Nov 23 '18 at 6:19
but the default keyword ispublic. isn't it? but it throw error in angular and asked to setprivate. btw this thumb rule only applicable in constructor body only. any other method of the class must access the service only viathisonly. is that right?
– diEcho
Nov 23 '18 at 7:24
1
There is no default keyword. If you don't explicitly define it, typescript will not create a field for you. Also, yes if you need to access any property of a class, you HAVE to usethis. Within constructor, you don't need to usethisbecause it is also a parameter of the constructor.
– Bunyamin Coskuner
Nov 23 '18 at 7:27
that makes perfect sense. Thanks one again.
– diEcho
Nov 23 '18 at 7:31
|
show 1 more 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%2f53441239%2fuse-of-this-in-constructor-in-refrence-with-dependencies-injection-in-angular%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
It is all about Typescript. When you use public, private or protected on a constructor parameters as follows
constructor(private logger: Logger) {}
In reality, Typescript creates a field with the same name and set it for you.
So, instead of writing following code you could simply write the code above
private logger: Logger;
constructor(logger: Logger) {
this.logger = logger;
}
Since, you already wrote private logger, you can simply use your field with this. It does not really matter how you use it within constructor.
There is a Typescript Playground where you can try this out and see it yourself. Whatever you type in the left box will be converted into plain JS (ES5) in the right box.
@Optional decorator just tells Angular that it is OK if it cannot find that object to inject.
Rule of thumb:
If you use private, protected or public on a any field and want to use it, always use this (within constructor)
If you didn’t mark the field with any of the keywords above, you cannot use this and cannot access that object outside of constructor.
If you need to access a property/method of a class, you HAVE to use this.
Thanks for the explanation but still confused whether to usethisor not within the constructor?
– diEcho
Nov 23 '18 at 6:15
I edited my answer, check it out @diEcho
– Bunyamin Coskuner
Nov 23 '18 at 6:19
but the default keyword ispublic. isn't it? but it throw error in angular and asked to setprivate. btw this thumb rule only applicable in constructor body only. any other method of the class must access the service only viathisonly. is that right?
– diEcho
Nov 23 '18 at 7:24
1
There is no default keyword. If you don't explicitly define it, typescript will not create a field for you. Also, yes if you need to access any property of a class, you HAVE to usethis. Within constructor, you don't need to usethisbecause it is also a parameter of the constructor.
– Bunyamin Coskuner
Nov 23 '18 at 7:27
that makes perfect sense. Thanks one again.
– diEcho
Nov 23 '18 at 7:31
|
show 1 more comment
It is all about Typescript. When you use public, private or protected on a constructor parameters as follows
constructor(private logger: Logger) {}
In reality, Typescript creates a field with the same name and set it for you.
So, instead of writing following code you could simply write the code above
private logger: Logger;
constructor(logger: Logger) {
this.logger = logger;
}
Since, you already wrote private logger, you can simply use your field with this. It does not really matter how you use it within constructor.
There is a Typescript Playground where you can try this out and see it yourself. Whatever you type in the left box will be converted into plain JS (ES5) in the right box.
@Optional decorator just tells Angular that it is OK if it cannot find that object to inject.
Rule of thumb:
If you use private, protected or public on a any field and want to use it, always use this (within constructor)
If you didn’t mark the field with any of the keywords above, you cannot use this and cannot access that object outside of constructor.
If you need to access a property/method of a class, you HAVE to use this.
Thanks for the explanation but still confused whether to usethisor not within the constructor?
– diEcho
Nov 23 '18 at 6:15
I edited my answer, check it out @diEcho
– Bunyamin Coskuner
Nov 23 '18 at 6:19
but the default keyword ispublic. isn't it? but it throw error in angular and asked to setprivate. btw this thumb rule only applicable in constructor body only. any other method of the class must access the service only viathisonly. is that right?
– diEcho
Nov 23 '18 at 7:24
1
There is no default keyword. If you don't explicitly define it, typescript will not create a field for you. Also, yes if you need to access any property of a class, you HAVE to usethis. Within constructor, you don't need to usethisbecause it is also a parameter of the constructor.
– Bunyamin Coskuner
Nov 23 '18 at 7:27
that makes perfect sense. Thanks one again.
– diEcho
Nov 23 '18 at 7:31
|
show 1 more comment
It is all about Typescript. When you use public, private or protected on a constructor parameters as follows
constructor(private logger: Logger) {}
In reality, Typescript creates a field with the same name and set it for you.
So, instead of writing following code you could simply write the code above
private logger: Logger;
constructor(logger: Logger) {
this.logger = logger;
}
Since, you already wrote private logger, you can simply use your field with this. It does not really matter how you use it within constructor.
There is a Typescript Playground where you can try this out and see it yourself. Whatever you type in the left box will be converted into plain JS (ES5) in the right box.
@Optional decorator just tells Angular that it is OK if it cannot find that object to inject.
Rule of thumb:
If you use private, protected or public on a any field and want to use it, always use this (within constructor)
If you didn’t mark the field with any of the keywords above, you cannot use this and cannot access that object outside of constructor.
If you need to access a property/method of a class, you HAVE to use this.
It is all about Typescript. When you use public, private or protected on a constructor parameters as follows
constructor(private logger: Logger) {}
In reality, Typescript creates a field with the same name and set it for you.
So, instead of writing following code you could simply write the code above
private logger: Logger;
constructor(logger: Logger) {
this.logger = logger;
}
Since, you already wrote private logger, you can simply use your field with this. It does not really matter how you use it within constructor.
There is a Typescript Playground where you can try this out and see it yourself. Whatever you type in the left box will be converted into plain JS (ES5) in the right box.
@Optional decorator just tells Angular that it is OK if it cannot find that object to inject.
Rule of thumb:
If you use private, protected or public on a any field and want to use it, always use this (within constructor)
If you didn’t mark the field with any of the keywords above, you cannot use this and cannot access that object outside of constructor.
If you need to access a property/method of a class, you HAVE to use this.
edited Nov 23 '18 at 7:27
answered Nov 23 '18 at 6:00
Bunyamin CoskunerBunyamin Coskuner
4,06211036
4,06211036
Thanks for the explanation but still confused whether to usethisor not within the constructor?
– diEcho
Nov 23 '18 at 6:15
I edited my answer, check it out @diEcho
– Bunyamin Coskuner
Nov 23 '18 at 6:19
but the default keyword ispublic. isn't it? but it throw error in angular and asked to setprivate. btw this thumb rule only applicable in constructor body only. any other method of the class must access the service only viathisonly. is that right?
– diEcho
Nov 23 '18 at 7:24
1
There is no default keyword. If you don't explicitly define it, typescript will not create a field for you. Also, yes if you need to access any property of a class, you HAVE to usethis. Within constructor, you don't need to usethisbecause it is also a parameter of the constructor.
– Bunyamin Coskuner
Nov 23 '18 at 7:27
that makes perfect sense. Thanks one again.
– diEcho
Nov 23 '18 at 7:31
|
show 1 more comment
Thanks for the explanation but still confused whether to usethisor not within the constructor?
– diEcho
Nov 23 '18 at 6:15
I edited my answer, check it out @diEcho
– Bunyamin Coskuner
Nov 23 '18 at 6:19
but the default keyword ispublic. isn't it? but it throw error in angular and asked to setprivate. btw this thumb rule only applicable in constructor body only. any other method of the class must access the service only viathisonly. is that right?
– diEcho
Nov 23 '18 at 7:24
1
There is no default keyword. If you don't explicitly define it, typescript will not create a field for you. Also, yes if you need to access any property of a class, you HAVE to usethis. Within constructor, you don't need to usethisbecause it is also a parameter of the constructor.
– Bunyamin Coskuner
Nov 23 '18 at 7:27
that makes perfect sense. Thanks one again.
– diEcho
Nov 23 '18 at 7:31
Thanks for the explanation but still confused whether to use
this or not within the constructor?– diEcho
Nov 23 '18 at 6:15
Thanks for the explanation but still confused whether to use
this or not within the constructor?– diEcho
Nov 23 '18 at 6:15
I edited my answer, check it out @diEcho
– Bunyamin Coskuner
Nov 23 '18 at 6:19
I edited my answer, check it out @diEcho
– Bunyamin Coskuner
Nov 23 '18 at 6:19
but the default keyword is
public. isn't it? but it throw error in angular and asked to set private. btw this thumb rule only applicable in constructor body only. any other method of the class must access the service only via this only. is that right?– diEcho
Nov 23 '18 at 7:24
but the default keyword is
public. isn't it? but it throw error in angular and asked to set private. btw this thumb rule only applicable in constructor body only. any other method of the class must access the service only via this only. is that right?– diEcho
Nov 23 '18 at 7:24
1
1
There is no default keyword. If you don't explicitly define it, typescript will not create a field for you. Also, yes if you need to access any property of a class, you HAVE to use
this. Within constructor, you don't need to use this because it is also a parameter of the constructor.– Bunyamin Coskuner
Nov 23 '18 at 7:27
There is no default keyword. If you don't explicitly define it, typescript will not create a field for you. Also, yes if you need to access any property of a class, you HAVE to use
this. Within constructor, you don't need to use this because it is also a parameter of the constructor.– Bunyamin Coskuner
Nov 23 '18 at 7:27
that makes perfect sense. Thanks one again.
– diEcho
Nov 23 '18 at 7:31
that makes perfect sense. Thanks one again.
– diEcho
Nov 23 '18 at 7:31
|
show 1 more 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%2f53441239%2fuse-of-this-in-constructor-in-refrence-with-dependencies-injection-in-angular%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