Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access service into static method in Angular 5

Tags:

typescript

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.

like image 808
GreatHawkeye Avatar asked Dec 13 '17 10:12

GreatHawkeye


People also ask

What is static service in angular?

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.

How do I create a static method in TypeScript?

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.

What is static TypeScript?

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.

What are static functions?

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.


1 Answers

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(....);
like image 151
synapse Avatar answered Oct 18 '22 07:10

synapse