Page Contents

Home > @loopback/core > Application > service

Application.service() method

Add a service to this application.

Signature:

service<S>(cls: Constructor<S> | Constructor<Provider<S>>, name?: string | ServiceOptions): Binding<S>;

Parameters

Parameter Type Description
cls Constructor<S> | Constructor<Provider<S>> The service or provider class
name string | ServiceOptions  

Returns:

Binding<S>

Example

// Define a class to be bound via ctx.toClass()
@bind({scope: BindingScope.SINGLETON})
export class LogService {
  log(msg: string) {
    console.log(msg);
  }
}

// Define a class to be bound via ctx.toProvider()
const uuidv4 = require('uuid/v4');
export class UuidProvider implements Provider<string> {
  value() {
    return uuidv4();
  }
}

// Register the local services
app.service(LogService);
app.service(UuidProvider, 'uuid');

export class MyController {
  constructor(
    @inject('services.uuid') private uuid: string,
    @inject('services.LogService') private log: LogService,
  ) {
  }

  greet(name: string) {
    this.log(`Greet request ${this.uuid} received: ${name}`);
    return `${this.uuid}: ${name}`;
  }
}