Создание первого приложения на Angular. Получение данных и отрисовка material table

Главная » Видеоуроки » JavaScript » Создание первого приложения на Angular. Получение данных и отрисовка material table

Мы продолжаем разработку нашего первого Angular приложения. В этом видео мы получим данные с бэкенда (https://jsonplaceholder.typicode.com/) и добавим отрисовку данных, используя angular material table.

users-service.ts

import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {User} from '../../core/models/User';

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

  private readonly api = 'https://jsonplaceholder.typicode.com/'

  constructor(private http: HttpClient) {
  }

  getUsers(): Observable<User[]> {
      return this.http.get<User[]>(`${this.api}/users`);
  }

}

users.ts

import {ChangeDetectionStrategy, Component, inject, OnInit} from '@angular/core';
import {UsersService} from '../../services/users-service';
import {Observable, of} from 'rxjs';
import {AsyncPipe, JsonPipe} from '@angular/common';
import {
  MatCell,
  MatCellDef,
  MatColumnDef,
  MatHeaderCell,
  MatHeaderCellDef, MatHeaderRow,
  MatHeaderRowDef, MatRow, MatRowDef,
  MatTable
} from '@angular/material/table';
import {User} from '../../../core/models/User';

const ELEMENT_DATA = [
  {position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'},
  {position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'},
  {position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'},
  {position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be'},
  {position: 5, name: 'Boron', weight: 10.811, symbol: 'B'},
  {position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C'},
  {position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N'},
  {position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O'},
  {position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F'},
  {position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne'},
];

@Component({
  selector: 'app-users',
  templateUrl: './users.html',
  styleUrl: './users.scss',
  imports: [AsyncPipe, JsonPipe, MatHeaderRowDef, MatTable, MatHeaderCell, MatHeaderCellDef, MatHeaderCellDef, MatColumnDef, MatCellDef, MatCell, MatHeaderRow, MatRowDef, MatRow]
})
export class Users implements OnInit{

  protected users$: Observable<User[]> = of([]);

  private users = inject(UsersService);

  protected displayedColumns: string[] = ['name', 'email', 'phone'];
  dataSource = ELEMENT_DATA;

  ngOnInit(): void {
    this.users$ = this.users.getUsers();
  }
}

0 Comments

Submit a Comment

Ваш адрес email не будет опубликован. Обязательные поля помечены *


Срок проверки reCAPTCHA истек. Перезагрузите страницу.

Pin It on Pinterest

Share This