Angular. Introduction to services

Home » Tutorials » JavaScript » Angular. Introduction to services
Services in Angular are simple classes, who make specific non-component operations (calculations, read data from remote HTTP server and etc).
Services have the special decorator @Injectable(), which define this class as the service. The decorator has a param providedIn, which defines service area of use. The service includes to component with using dependency injection process.

Code lesson (service class)

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class UserService {

  constructor() { }

  getUser(): any {
      return {login: 'login', roles: ['admin', 'editor']};
  }

 }

Code lesson (component class)

import { Component } from '@angular/core';
import { UserService } from './user.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  // providers: [UserService]
})
export class AppComponent {
  title = 'Click me';
  user: any;

  constructor(private _userService: UserService){ 
  }

  getUser() {
    this.user = this._userService.getUser();
    console.log(this.user);
  }

  getString() {
    return 'Angular works';
  }
}

Code lesson (component template)

<button (click)="getUser()">{{title}}</button>   

<p>{{1+1}}</p>

<p>{{getString()}}</p>

<p>{{user.login}}</p>

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.

Pin It on Pinterest

Share This