Readdy Write  
0,00 €
Your View Money
Views: Count
Self 20% 0
Your Content 60% 0

Users by Links 0
u1*(Content+Views) 10% 0
Follow-Follower 0
s2*(Income) 5% 0

Count
Followers 0
Login Register as User

Angular: Datensatz lesen von Web Api und anzeigen in Angular

08.02.2021 (👁795)

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((responseTimeRecord=> {

          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 { BehaviorSubjectObservable } from 'rxjs';

import { catchErrormapstartWithswitchMap } 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 httpHttpClient) { }

  //----< 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((responseTimeRecord[]) => {

          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((responseTimeRecord=> {

          return response;

        }

        )

      )

  }

  //----</ get_Dateset >----

}

 

 

 

 

 

Code behind Component.ts

import { Injectable } from '@angular/core';

import { HttpClient } from "@angular/common/http";

import { BehaviorSubjectObservable } from 'rxjs';

import { catchErrormapstartWithswitchMap } 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 httpHttpClient) { }

  //----< 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((responseTimeRecord[]) => {

          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((responseTimeRecord=> {

          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 {

        margin4px;

        padding4px;

        /* background-color: #eeeeee; */

        width600px;

    }

    p {

        colorblue;

    }

    ::ng-deep .mat-focused .mat-form-field-label {

        /*change color of label*/

        colorrgb(253250244!important;

    }

    ::ng-deep.mat-form-field-underline {

        /*change color of underline*/

        background-colorgreen !important;

    }

    ::ng-deep.mat-form-field-ripple {

        /*change color of underline when focused*/

        background-colorgreen !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>&nbsp;

        <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>&nbsp;

        <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; }

    }

}