Создание первого приложения на Angular. Отрисовка страницы юзера

Главная » Видеоуроки » JavaScript » Создание первого приложения на Angular. Отрисовка страницы юзера

Мы продолжаем разработку нашего первого Angular приложения. Сегодня мы закончим страницу юзера, используя для отрисовки данных angular material компоненты.

user.ts

import {Component, inject, OnInit} from '@angular/core';
import {UsersService} from '../../services/users-service';
import {ActivatedRoute} from '@angular/router';
import {catchError, Observable, of} from 'rxjs';
import {UserDto} from '../../../core/models/User';
import {AsyncPipe} from '@angular/common';
import {MatCard, MatCardContent, MatCardHeader} from '@angular/material/card';
import {MatSnackBar} from '@angular/material/snack-bar';

@Component({
  selector: 'app-user',
  imports: [
    AsyncPipe,
    MatCard,
    MatCardHeader,
    MatCardContent
  ],
  templateUrl: './user.html',
  styleUrl: './user.scss',
})
export class User implements OnInit{

  protected user$: Observable<UserDto | null> = of(null);

  private users = inject(UsersService);
  private route = inject(ActivatedRoute);
  private snackBar = inject(MatSnackBar);

  public ngOnInit() {
    const userId = +this.route.snapshot.params['id'];

    if (userId > 0) {
      this.user$ = this.users.getUserById(userId).pipe(
        catchError(err => {
          this.snackBar.open('User not found', '', {
            duration: 3000
          });
          return of(null);
        })
      );
    } else {
      this.snackBar.open('User not found', '', {
        duration: 3000
      });
    }
  }

}

user.html

@let user = user$ | async;

@if (user) {
  <mat-card>
    <mat-card-header>{{user.name}}</mat-card-header>
    <mat-card-content>
      <p>User email: {{user.email}}</p>
      <p>User phone: {{user.phone}}</p>
    </mat-card-content>
  </mat-card>
}

users-service.ts

import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {catchError, map, Observable, of} from 'rxjs';
import {UserDto} from '../../core/models/User';

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

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

  constructor(private http: HttpClient) {
  }

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

  getUserById(id: number): Observable<UserDto> {
    return this.http.get<UserDto>(`${this.api}/users/${id}`);
  }

}

0 Comments

Submit a Comment

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


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

Pin It on Pinterest

Share This