constructor (service: MyService) {}
ngOnInit() {
this.service.init();
}
In the above code, I'm getting:-
Property `service` does not exist on type 'MyComponment'
Yet, if I declare service
as private
it works. What is going on here?
--
[Angular 8.2.12, TypeScript 3.5.3]
From the docs :
Parameter properties are declared by prefixing a constructor parameter with an accessibility modifier or
readonly
, or both. Usingprivate
for a parameter property declares and initializes a private member; likewise, the same is done forpublic
,protected
, andreadonly
.
Without the prefix, the constructor parameter is nothing more than a method parameter, and you would have to manually assign it to a declared class property from the constructor itself.
Property
service
does not exist on type 'MyComponment'
Error is because you are trying to access service
outside of the class's constructor. And by design if you are willing to use some variable/initilization outside the constructor you have to use some access modifiers like private
public
etc.
constructor (private service: MyService) {}
ngOnInit() {
this.service.init(); // valid
}
Here
constructor (service: MyService) {}
ngOnInit() {
this.service.init(); // Invalid
}
ngOnInit
is outside/different method of the class not inner from the constructor so in order to access using this
keyword you have to use some access modifier prefix while initilization in the constructor.
But this will work if you do it like this -
constructor (service: MyService) {
service.init(); // valid
}
In simpler words you can follow this small example -
I assume you mean putting the private
like this:
constructor (private service: MyService) {}
That's actually a shorthand in TypeScript.
Similar to
constructor (public service: MyService) {}
Its sugar so you don't have to do
class Foo {
private foo
public bar
constructor (foo, bar) {
this.foo = 1
this.bar = 2
}
}
Instead you would do:
class Foo {
constructor (private foo = 1, public bar = 2) {}
}
When the TypeScript is compiled into JS, it puts both public and privates as regular (public) instance properties. Because JS doesn't actually have the concept of private class members ( not yet anyway )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.