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

Asp.Net Core mit Angular Tabelle mit Angular Material.Table

27.01.2021 (πŸ‘25079)


 

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 {

  idtimeRecordnumber;

  iduserGuidstring;

  dtStartDate;

  dtEndeDate;

  projectstring;

  detailsstring;

  dtEditDate;

}

export interface TimeRecordApi {

  itemsTimeRecord[];

  total_countnumber;

}

Service.ts

Abholen der Web API Daten mit httpClient

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

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

import { BehaviorSubjectObservable } from 'rxjs'

import {catchErrormapstartWithswitchMapfrom '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;

  constructorprivate httpHttpClient  ) { }

  getData():Observable<TimeRecord[]>{

    

    return this.http

    .get<TimeRecord[]>(this.URL)

    .pipe(

    map((responseTimeRecord[]) => {

           return response ; 

         }

        )

    )

  }

}

Component.ts

Typescript Datei laden der Web Api Daten ΓΌber Service. Ausgeben an Angular Table

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

import { TimerecordsService } from "../../services/timerecords.service";

import { TimeRecord } from '../../models/time-records.model';

import { pipe } from 'rxjs';

import { catchErrormapstartWithswitchMap } from 'rxjs/operators';

import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';

import {ThemePalettefrom '@angular/material/core';

import {ProgressSpinnerModefrom '@angular/material/progress-spinner';

// import { MatPaginator } from '@angular/material/paginator';

// import { MatSort } from '@angular/material/sort';

// import { MatTableDataSource } from '@angular/material/table';

import { mergeObservableof 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 timerecordsServiceTimerecordsService) { }

  //< variables >

  displayedColumnsstring[] = ['project''details''dtStart''dtEnd'];

  //dataSource: TimeRecord;

  dataSource = new MatTableDataSource<TimeRecord>();

  resultsLength = 0;

  isLoadingResults = true;

  isHttpError = false;

  //</ variables >

  colorThemePalette = 'primary';

  modeProgressSpinnerMode = '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 {ThemePalettefrom '@angular/material/core';

import {ProgressSpinnerModefrom '@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

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

  }