Backend: Asp.Net Core
Frontend: Angular 10
Zeigt die Anbindung von Daten von Asp.Net Core Web API und Darstellung als Angular Material Table
Asp.Net Controller
Gibt die Web API als JSon Daten aus (Siehe Swagger Json unten)
using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using APITimerecord.Models;
namespace APITimerecord.Controllers { [Route("api/[controller]")] [ApiController] public class TimeRecordsController : ControllerBase { private readonly API_TimeRecordContext _context;
public TimeRecordsController(API_TimeRecordContext context) { _context = context; }
// GET: api/TimeRecords [HttpGet] public async Task<ActionResult<IEnumerable<TimeRecord>>> GetTimeRecords() { return await _context.TimeRecords.ToListAsync(); } |
Asp.Net Model
Daten Model unter Asp.Net Core
using System; using System.Collections.Generic;
#nullable disable
namespace APITimerecord.Models { public partial class TimeRecord { public int IdtimeRecord { get; set; } public string IduserGuid { get; set; } public DateTime? DtStart { get; set; } public DateTime? DtEnd { get; set; } public string Project { get; set; } public string Details { get; set; } public DateTime? DtEdit { get; set; } } } |
Daten Model
Als Interface unter Angular
export interface TimeRecord {
idtimeRecord: number; iduserGuid: string; dtStart: Date; dtEnde: Date; project: string; details: string; dtEdit: Date; }
export interface TimeRecordApi { items: TimeRecord[]; total_count: number; } |
Service.ts
Abholen der Web API Daten mit httpClient
import { Injectable } from '@angular/core'; import { HttpClient } from "@angular/common/http"; import { BehaviorSubject, Observable } from 'rxjs'; import {catchError, map, startWith, switchMap} from 'rxjs/operators'; import { TimeRecord } from '../models/time-records.model';
@Injectable({ providedIn: 'root' }) export class TimerecordsService {
private URL : string="https://localhost:44388/api/TimeRecords"; resultsLength = 0; isLoadingResults = true; isRateLimitReached = false;
constructor( private http: HttpClient ) { }
getData():Observable<TimeRecord[]>{
return this.http .get<TimeRecord[]>(this.URL) .pipe( map((response: TimeRecord[]) => { return response ; } ) ) } } |
Component.ts
Typescript Datei laden der Web Api Daten ΓΌber Service. Ausgeben an Angular Table
import { Component, ViewChild, OnInit, AfterViewInit } from '@angular/core'; import { TimerecordsService } from "../../services/timerecords.service"; import { TimeRecord } from '../../models/time-records.model'; import { pipe } from 'rxjs'; import { catchError, map, startWith, switchMap } from 'rxjs/operators'; import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; import {ThemePalette} from '@angular/material/core'; import {ProgressSpinnerMode} from '@angular/material/progress-spinner'; // import { MatPaginator } from '@angular/material/paginator'; // import { MatSort } from '@angular/material/sort'; // import { MatTableDataSource } from '@angular/material/table';
import { merge, Observable, of as observableOf } from 'rxjs'; import { MatTableDataSource } from '@angular/material/table';
@Component({ selector: 'app-list-time-records', templateUrl: './list-time-records.component.html', styleUrls: ['./list-time-records.component.css'] })
export class ListTimeRecordsComponent implements OnInit { //========< class: Compontent >======== constructor(public timerecordsService: TimerecordsService) { }
//< variables > displayedColumns: string[] = ['project', 'details', 'dtStart', 'dtEnd']; //dataSource: TimeRecord; dataSource = new MatTableDataSource<TimeRecord>(); resultsLength = 0; isLoadingResults = true; isHttpError = false; //</ variables >
color: ThemePalette = 'primary'; mode: ProgressSpinnerMode = 'indeterminate';
//==< events >== ngOnInit() { this.load_DataSource(); } //==</ events >==
//#region //====< functions >==== load_DataSource() { //--------< load_DataSource() >-------- this.isLoadingResults = true; merge() .pipe( startWith({}), switchMap(() => { this.isLoadingResults = true; return this.timerecordsService.getData() }), catchError(() => { this.isLoadingResults = true; this.isHttpError = true; return observableOf([]); }) ).subscribe(res => {this.dataSource.data = res as TimeRecord[]} )
//--------</ load_DataSource() >-------- } //====</ functions >==== //#endregion
//========</ class: Compontent >======== } |
Component.html
Mit der Angular.Material Table
File: List-time-records.component.html
<div class="example-container mat-elevation-z8">
<div class="example-rate-limit-reached" *ngIf="isHttpError">Api Data error</div>
<p>List</p>
<table mat-table [dataSource]="dataSource" class="example-table" matSort matSortActive="created" matSortDisableClear matSortDirection="desc">
<ng-container matColumnDef="project"> <th mat-header-cell *matHeaderCellDef> project </th> <td mat-cell *matCellDef="let element"> {{ element.project }} </td> </ng-container>
<!-- Weight Column --> <ng-container matColumnDef="details"> <th mat-header-cell *matHeaderCellDef> details </th> <td mat-cell *matCellDef="let element"> {{element.details}} </td>
</ng-container>
<!-- Name Column --> <ng-container matColumnDef="dtStart"> <th mat-header-cell *matHeaderCellDef> dtStart </th> <td mat-cell *matCellDef="let element"> {{element.dtStart}} </td> </ng-container>
<!-- Weight Column --> <ng-container matColumnDef="dtEnd"> <th mat-header-cell *matHeaderCellDef> dtEnd </th> <td mat-cell *matCellDef="let element"> {{element.dtEnd}} </td> </ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr> </table>
</div>
<mat-progress-spinner></mat-progress-spinner>
|
App.Modul.ts
Einbinden der Angular Module und Material Module
import { BrowserModule } from '@angular/platform-browser'; import { NgModule,CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; import { TimerecordsService } from "./services/timerecords.service";
import { AppRoutingModule } from './app-routing.module'; import { HttpClientModule } from '@angular/common/http'; //*, import { MatPaginatorModule } from '@angular/material/paginator'; import { MatSortModule } from '@angular/material/sort'; import { MatTableModule } from '@angular/material/table' import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import {ThemePalette} from '@angular/material/core'; import {ProgressSpinnerMode} from '@angular/material/progress-spinner';
//import { BehaviorSubject } from 'rxjs'; import { AppComponent } from './app.component'; import { NavbarComponent } from './components/navbar/navbar.component'; import { ListTimeRecordsComponent } from './components/list-time-records/list-time-records.component';
@NgModule({ declarations: [ AppComponent, NavbarComponent, ListTimeRecordsComponent ], imports: [ BrowserModule, HttpClientModule, AppRoutingModule, MatPaginatorModule , MatSortModule , MatTableModule, MatProgressSpinnerModule, BrowserAnimationsModule ], providers: [TimerecordsService], bootstrap: [AppComponent] }) export class AppModule { }
|
Web API Daten
Json Daten via Swagger
URL: https://localhost:44388/api/TimeRecords
[ { "idtimeRecord": 1, "iduserGuid": null, "dtStart": "2021-01-20T08:00:00", "dtEnd": "2021-01-20T12:01:00", "project": "API TimeRecords", "details": "Tabellen in SQL", "dtEdit": null }, { "idtimeRecord": 2, "iduserGuid": null, "dtStart": "2021-01-21T08:10:00", "dtEnd": "2021-01-21T16:03:00", "project": "Angular", "details": "Daten mit HttpClient laden", "dtEdit": null }, { "idtimeRecord": 3, "iduserGuid": null, "dtStart": "2021-01-22T09:00:00", "dtEnd": "2021-01-22T17:00:00", "project": "Angular", "details": "Material einbauen. Anbinden an Daten", "dtEdit": null } |