user13821408
user13821408

Reputation:

How to initializate service from component?

I use separate instanse of service in each componnents:

@Component({
    selector: 'app-orders',
    templateUrl: './orders.component.html',
    styleUrls: ['./orders.component.scss'],
    providers: [PaginationService],
})

Service pagination is:

@Injectable()
export class PaginationService {
    private offset: number;
    private limit: number;

    constructor() {
        this.offset = 0;
        this.limit = 20;
    }
  }

As you can see service has initialization in constructor. How to initializate service from specific component like:

providers: [PaginationService(0, 20)],

Upvotes: 0

Views: 67

Answers (3)

Joel Balmer
Joel Balmer

Reputation: 1479

One way would be to inject the service as normal, then in your component's constructor you could call a method on the service that performs setup with the values provided, something along the lines of:

@Component({
    selector: 'app-orders',
    templateUrl: './orders.component.html',
    styleUrls: ['./orders.component.scss']
})
export class OrdersComponent implements OnInit {

  constructor(private paginationService: PaginationService) {
    this.paginationService.setup(0, 20);
  }

  ngOnInit() { }

}

Upvotes: 1

Danilo Torchio
Danilo Torchio

Reputation: 401

You can use a factory provider, like this:

@Component({
  selector: 'app-orders',
  templateUrl: './orders.component.html',
  styleUrls: ['./orders.component.scss'],
  providers: [
    {
      provide: PaginationService,
      useFactory: () => new PaginationService(0, 20)
    }
  ],
})

You can find more samples in the Angular docs here.

Upvotes: 2

nevzatopcu
nevzatopcu

Reputation: 1085

You can create a InjectionToken for them.

injection.tokens.ts

import { InjectionToken } from "@angular/core";

export const PAGINATION_OFFSET = new InjectionToken<string>('PaginationOffset');
export const PAGINATION_LIMIT = new InjectionToken<string>('PaginationLimit');

component.ts

import {PAGINATION_OFFSET, PAGINATION_LIMIT} from "<injection.tokens>"

    @Component({
      selector: 'stackoverflow',
      template: ``,
      styles: [`h1 { font-family: Lato; }`],
      providers: [
        PaginationService,
        {
          provide: PAGINATION_OFFSET,
          useValue: 10
        },
        {
          provide: PAGINATION_LIMIT,
          useValue: 50
        }
      ]
    })

pagination.service

   import {PAGINATION_OFFSET, PAGINATION_LIMIT} from "./injection-tokens";
    
    @Injectable()
    export class PaginationService {
      constructor(@Inject(PAGINATION_OFFSET) private offset: number, @Inject(PAGINATION_LIMIT) private limit: number ) {}
}

You can check working Stackblitz

Upvotes: 1

Related Questions