Page Contents

Home > @loopback/core > Application > service

Application.service() method

Add a service to this application.

Signature:

service<S>(cls: ServiceOrProviderClass<S>, nameOrOptions?: string | ServiceOptions): Binding<S>;

Parameters

Parameter Type Description
cls ServiceOrProviderClass<S> The service or provider class
nameOrOptions string | ServiceOptions (Optional)

Returns:

Binding<S>

Example

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

// Define a class to be bound via ctx.toProvider()
import {v4 as uuidv4} from 'uuid';
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}`;
  }
}