Angular: Datesatz lesen von Web Api lesen und anzeigen
Mit Angular als Frontend kann man Daten eines Asp.Net Core servers anzeigen und bearbeiten.
Hier wird ein Datensatz mit einer ID = 1 abgeholt vom Web API Frontend des Asp.Net Core Servers mittels eines Angular .Service.ts Web Clients und als Daten an die Componente übergeben zur Anzeige
Data Service get web data
In the angular .service.ts file, the angular client gets the recordset as Json from the web api
get_Dataset(ID : number): Observable<TimeRecord> {
return this.http .get<TimeRecord>(this.url_Api_Base + "/" + ID ) .pipe( map((response: TimeRecord) => { return response; } ) ) } |
Componet.ts calls for recordset
The component.ts calls the service to get the 1-dataset from the web-api
load_DataSource() { //--------< load_DataSource() >-------- this.isLoadingResults = true; merge() .pipe( startWith({}), switchMap(() => { this.isLoadingResults = true; return this.timerecordsService.get_Dataset(this.idtimeRecord) }), catchError(() => { this.isLoadingResults = true; this.isHttpError = true; return observableOf([]); }) ).subscribe(response => { //--< async response >-- this.timeRecord = response as TimeRecord
//console.log("response=" + response.toString()); this.map_Data(); //*map json to local variables //--</ async response >-- }
); //--------</ load_DataSource() >-------- }
|
Map Data Funktion
Die Daten von dem Web Client Service müssen eventuell auf die Ausgabe angepasst werden. Das macht man am Besten in einer map() funktion
map_Data() { //--------< map_Data() >-------- //*map Recordset to local variables console.log("timerecord=" + this.timeRecord); this.idtimeRecord = this.timeRecord.idtimeRecord; this.iduserguid = this.timeRecord.iduserguid; this.project = this.timeRecord.project; this.details = this.timeRecord.details; this.dtStart = new Date(this.timeRecord.dtStart); // this.dtEnd = new Date(this.timeRecord.dtEnd); //console.log("dtStart=" + this.dtStart.toString()); console.log("dtEnd=" + this.dtEnd.toString());
//< convert iso Date > //*convert Iso-Date-Time to Javascript Date: 2021-01-20T08:00:00 this.sDateStart = this.get_Date_String_from_Date(this.dtStart); this.sTimeStart = this.get_Time_String_from_Date(this.dtStart); this.sTimeEnd = this.get_Time_String_from_Date(this.dtEnd); this.sTimeDriving = this.get_Time_String_from_Float(this.DrivingTime); this.sTimePause = this.get_Time_String_from_Float(this.PauseTime); this.calculate_Duration(); //</ convert iso Date >
this.idtimeRecord = this.timeRecord.idtimeRecord; //--------</ map_Data() >-------- }
|
Server Asp.Net Code
Im Controller wird der Web API Daten wie folgt abgeholt
// GET: api/TimeRecords/5 [HttpGet("{id}")] public async Task<ActionResult<TimeRecord>> GetTimeRecord(int id) { var timeRecord = await _context.TimeRecords.FindAsync(id);
if (timeRecord == null) { return NotFound(); }
return timeRecord; } |
Kompletter File Code
Web Client Data Service
Service.ts
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/timerecords.model'; import { identifierModuleUrl } from '@angular/compiler';
@Injectable({ providedIn: 'root' }) export class TimerecordsService {
private url_Api_Base : string = "https://localhost:44388/api/TimeRecords";
resultsLength = 0; isLoadingResults = true; isRateLimitReached = false;
constructor(private http: HttpClient) { }
//----< get_Data_List >---- //*read web-API : entire List top20 get_Data_List(): Observable<TimeRecord[]> {
return this.http .get<TimeRecord[]>(this.url_Api_Base) .pipe( map((response: TimeRecord[]) => { return response; } ) ) } //----</ get_Data_List >----
//----< get_Dateset >---- //*read 1 Dataset from web-API get_Dataset(ID : number): Observable<TimeRecord> {
return this.http .get<TimeRecord>(this.url_Api_Base + "/" + ID ) .pipe( map((response: TimeRecord) => { return response; } ) ) } //----</ get_Dateset >----
} |
Code behind Component.ts
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/timerecords.model'; import { identifierModuleUrl } from '@angular/compiler';
@Injectable({ providedIn: 'root' }) export class TimerecordsService {
private url_Api_Base : string = "https://localhost:44388/api/TimeRecords";
resultsLength = 0; isLoadingResults = true; isRateLimitReached = false;
constructor(private http: HttpClient) { }
//----< get_Data_List >---- //*read web-API : entire List top20 get_Data_List(): Observable<TimeRecord[]> {
return this.http .get<TimeRecord[]>(this.url_Api_Base) .pipe( map((response: TimeRecord[]) => { return response; } ) ) } //----</ get_Data_List >----
//----< get_Dateset >---- //*read 1 Dataset from web-API get_Dataset(ID : number): Observable<TimeRecord> {
return this.http .get<TimeRecord>(this.url_Api_Base + "/" + ID ) .pipe( map((response: TimeRecord) => { return response; } ) ) } //----</ get_Dateset >----
} |
Output component.html
<div class="alert alert-success" *ngIf="isHttpError"> <p>web http request error</p> </div> <h3 class="page-title">Edit ID: {{ idtimeRecord }} </h3>
<style> div { margin: 4px; padding: 4px; /* background-color: #eeeeee; */ width: 600px; }
p { color: blue; }
::ng-deep .mat-focused .mat-form-field-label { /*change color of label*/ color: rgb(253, 250, 244) !important; }
::ng-deep.mat-form-field-underline { /*change color of underline*/ background-color: green !important; }
::ng-deep.mat-form-field-ripple { /*change color of underline when focused*/ background-color: green !important; ; } </style>
<form novalidate #f="ngForm" style="background-color: darkslategrey;"> <div> <mat-form-field style="width: 300px;"> <mat-label>project</mat-label> <input type="text" name="ctlproject" matInput [(ngModel)]="project" maxlength="50"> </mat-form-field> </div> <div> <mat-form-field style="width: 500px;"> <mat-label>details</mat-label> <input type="text" name="ctldetails" matInput [(ngModel)]="details" maxlength="255"> </mat-form-field> </div> <div> <mat-form-field style="width:130px;"> <mat-label>Date</mat-label> <input type="date" name="ctlsDateStart" matInput [(ngModel)]="sDateStart" > </mat-form-field> <mat-form-field style="width: 100px;"> <mat-label>Start</mat-label> <input type="time" name="ctlsTimeStart" matInput [(ngModel)]="sTimeStart" (change)="onInput_Change($event)"> </mat-form-field> <mat-form-field style="width: 100px;"> <mat-label>End</mat-label> <input type="time" name="ctlsTimeEnd" matInput [(ngModel)]="sTimeEnd" (change)="onInput_Change($event)"> </mat-form-field>
<mat-form-field style="width: 100px;"> <mat-label>+Driving</mat-label> <input type="time" name="ctlsDrivingTime" matInput [(ngModel)]="sTimeDriving" (change)="onInput_Change($event)"> </mat-form-field> <mat-form-field style="width: 100px;"> <mat-label>-Pause</mat-label> <input type="time" name="ctlsTimePause" matInput [(ngModel)]="sTimePause" (change)="onInput_Change($event)"> </mat-form-field>
<mat-form-field style="width: 100px;"> <mat-label>Duration</mat-label> <input disabled type="time" name="ctlsDuration" matInput [(ngModel)]="sDuration"> </mat-form-field> </div>
</form>
|
Server Code
Daten Model in 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 string Project { get; set; } public string Activity { get; set; } public DateTime? DtStart { get; set; } public DateTime? DtEnd { get; set; } public float? DrivingTime { get; set; } //*in hours 1,25 = 01:15 public float? PauseTime { get; set; } //*in hours 0,5 = 00:30 public DateTime? DtEdit { get; set; } } }
|