feat(angular): add data fetch example (#85)

This commit is contained in:
Israel de la Barrera
2022-05-22 11:17:39 +02:00
committed by GitHub
parent dde1ebf965
commit 7c516a7e58
5 changed files with 132 additions and 0 deletions

View File

@@ -0,0 +1,56 @@
export interface User {
gender: string;
name: {
title: string;
first: string;
last: string;
};
location: {
street: {
number: number;
name: string;
};
city: string;
state: string;
country: string;
postcode: number;
coordinates: {
latitude: string;
longitude: string;
};
timezone: {
offset: string;
description: string;
};
};
email: string;
login: {
uuid: string;
username: string;
password: string;
salt: string;
md5: string;
sha1: string;
sha256: string;
};
dob: {
date: Date;
age: number;
};
registered: {
date: Date;
age: number;
};
phone: string;
cell: string;
id: {
name: string;
value: string;
};
picture: {
large: string;
medium: string;
thumbnail: string;
};
nat: string;
}

View File

@@ -0,0 +1,25 @@
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { catchError, map, Subject } from 'rxjs';
import { User } from './user';
@Injectable({
providedIn: 'root'
})
export class UserService {
error$: Subject<any> = new Subject();
private users$ = this.HttpClient.get<{results: User[]; info: any}>('https://randomuser.me/api/?results=3')
.pipe(
map(x => x.results),
catchError(e => {this.error$.next(e); return []})
);
constructor(private HttpClient: HttpClient) {}
getUsers() {
return this.users$;
}
}

View File

@@ -0,0 +1,16 @@
<ul *ngIf="users$ | async as users; else loadingOrError">
<li *ngFor="let user of users">
<img [src]="user.picture.thumbnail" alt="user">
<p>{{user.name.first}} {{user.name.last}}</p>
</li>
</ul>
<ng-template #loadingOrError>
<p *ngIf="userService.error$ | async; else loading">
An error occured while fetching users
</p>
</ng-template>
<ng-template #loading>
Fetching users...
</ng-template>

View File

@@ -0,0 +1,16 @@
import { Component } from '@angular/core';
import { Observable } from 'rxjs';
import { User } from './user';
import { UserService } from './user.service';
@Component({
selector: 'app-users',
templateUrl: './users.component.html'
})
export class UsersComponent {
users$: Observable<User[]>
constructor(public userService: UserService) {
this.users$ = this.userService.getUsers();
}
}

View File

@@ -0,0 +1,19 @@
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { UserService } from './user.service';
import { UsersComponent } from './users.component';
@NgModule({
declarations: [
UsersComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [UserService],
bootstrap: [UsersComponent]
})
export class UsersModule { }