Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Oppiskele Creating and Using a Service | Services and Architecture
Building Backend Applications with Nest.js

bookCreating and Using a Service

Pyyhkäise näyttääksesi valikon

Open the src folder and create a new file:

users.service.ts

Add the following code:

import { Injectable } from '@nestjs/common';

@Injectable()
export class UsersService {
  getAllUsers() {
    return ['Alice', 'Bob'];
  }
}

This service contains the logic for working with users.

Now register the service in your module.

Open app.module.ts and update it:

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';

@Module({
  imports: [],
  controllers: [AppController, UsersController],
  providers: [AppService, UsersService],
})
export class AppModule {}

Here is what is happening:

  • providers: registers services used in the app;
  • UsersService: makes the service available for use.

Now use the service inside your controller:

import { Controller, Get } from '@nestjs/common';
import { UsersService } from './users.service';

@Controller('users')
export class UsersController {
  constructor(private usersService: UsersService) {}

  @Get()
  getUsers() {
    return this.usersService.getAllUsers();
  }
}

  • constructor: injects the service;
  • usersService: gives access to service methods;
  • getUsers(): calls the service and returns data.

Now when you open /users, the data comes from the service instead of being defined in the controller.

question mark

Where do you register a service so it can be used in Nest.js?

Valitse oikea vastaus

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 3. Luku 2

Kysy tekoälyä

expand

Kysy tekoälyä

ChatGPT

Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme

Osio 3. Luku 2
some-alt