I'm trying to access the service's reference into my static method like so :
export class myComponent {
constructor(private backend: BackendService) { }
public static myMethod() {
myComponent.backend.getData()
.subscribe(
data => { console.log(data) },
error => { console.error(error); }
);
}
}
I'm getting Property backend doesn't exist on type 'typeof myComponent'
How can I access backend
reference?
Thanks.
Static methods of a class, unlike instance methods, belong to (are visible on) the class itself (not an instance of it). They do not depend on the instance members of a class and will usually take input from the parameters, perform actions on it, and return some result. They act independently.
Identifying static methods If your function doesn't use the this keyword or any other class member, then it can be easily converted to a static function. To create a static function simply add the static keyword and call it directly from the class instead of calling it from the instance of the class.
TypeScript only supports static fields, which simply means you can access those fields without creating an instance of the class. If you use the declaration method above, you're forced to have all your public fields and methods as static, as you won't have any other way of accessing them.
A static method (or static function) is a method defined as a member of an object but is accessible directly from an API object's constructor, rather than from an object instance created via the constructor.
First and best solution : Just DON'T use a static method to consume your service.
Another one if you really want to make harder simple things ;)
@NgModule....
export class AppModule
{
constructor(public injector: Injector)
{
myComponent.injector = injector;
}
}
Then in your static method;
var myService = myComponent.injector.get(BackendService);
myService.getData(....);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With