简体   繁体   English

从Asp.net Core读取数据到Angular 7

[英]Read Data from Asp.net Core to Angular 7

Good day, 美好的一天,

I've been doing some self study in Angular 7 and Asp.net core web api. 我一直在Angular 7和Asp.net核心Web API中进行一些自学。

And now i want to read the result from asp.net core and show in in Angular 7. 现在我想从asp.net核心读取结果并在Angular 7中显示。

This is the code from Asp.net Core 这是来自Asp.net Core的代码

[HttpPost("DataCorrection")]
        public  IActionResult DataCorrection([FromBody] DataCorrectionDto data)
        {
            try
            {
                var request =  Request;
                var values =   _dataCorrection.GetDateRange(data.StartDate, data.EndDate);

                return Ok(values);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
                throw ex;
            }
        }

The method GetDateRange returns a List of DataCorrection Model 方法GetDateRange返回DataCorrection Model的列表

And this is my angular code 这是我的角度代码

     import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl,  } from '@angular/forms';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-data-correction',
  templateUrl: './data-correction.component.html',
  styleUrls: ['./data-correction.component.css']
})
export class DataCorrectionComponent implements OnInit {
  list: any[];
  selectedDate = new Date();
  form = new FormGroup({
    StartDate: new FormControl(),
    EndDate: new FormControl()
  });

  constructor(private http: HttpClient) { }
  ngOnInit() {
  }

  onSubmit() {
    this.http.post('http://localhost:5000/api/DataCorrection/DataCorrection', this.form.value)
    .toPromise()
    .then(res => {
      this.list = res as any[];
      console.log('Called');
      });
  }

}

And this is the Html Code 这是HTML代码

<form [formGroup]="form" (ngSubmit)="onSubmit()">
    <!-- <input formControlName="first" [(ngModel)]="value"> -->
    <mat-form-field>
      <input matInput formControlName="StartDate"  [matDatepicker]="StartDate" placeholder="Start date">
      <mat-datepicker-toggle matSuffix [for]="StartDate"></mat-datepicker-toggle>
      <mat-datepicker #StartDate  ></mat-datepicker>
    </mat-form-field>

    <mat-form-field>
        <input matInput formControlName="EndDate"   [matDatepicker]="EndDate" placeholder="End date">
        <mat-datepicker-toggle matSuffix [for]="EndDate"></mat-datepicker-toggle>
        <mat-datepicker #EndDate  ></mat-datepicker>
      </mat-form-field>
    <div class="form-group">
      <button class="btn btn-primary">Submit</button>
  </div>
  </form>

  <tr *ngFor="let pd of list">
      <td >{{pd.ActualLogin}}</td>
      <td >{{pd.ActualLogout}}</td>
      <td >{{pd.ShiftLogin}}</td>
      <td>
        <i class="far fa-trash-alt fa-lg text-danger" ></i>
      </td>
    </tr>

And now how can i read it properly so that i can load it in a table. 现在如何正确读取它,以便可以将其加载到表中。

With the code above. 上面的代码。 It doesn't even populate the table. 它甚至不填充表格。 But it calls the console.log 但是它调用console.log

I tried searching for a solution for hours now. 我尝试搜索解决方案已有几个小时了。 But i'm lost. 但是我迷路了。 I don't understand the tutorials and i can't make it work. 我不了解这些教程,因此无法正常工作。

This is the response from my web api. 这是我的Web API的响应。 I read it from the response tab in the chrome web browser 我是从Chrome网络浏览器的“ response标签中读取的

在此处输入图片说明

{"emp_Id":963,"actualLogin":"05:00:11","actualLogout":"05:01:00","shiftLogin":"05:00:00","shiftLogout":"13:00:00","date":"2019-04-03T00:00:00Z"}

This data is what i want to be populated in the table 我要在表中填充此数据

Thank you. 谢谢。

I don't think this was the problem, 我不认为这是问题所在

there is spell mistake in your template, pd.ActualLogin but actually in JSON response it is spelled as actualLogin . 您的模板pd.ActualLogin存在拼写错误,但实际上在JSON响应中,它拼写为actualLogin Change your template to 将模板更改为

   <tr *ngFor="let pd of list">
      <td >{{pd.actualLogin}}</td>
      <td >{{pd.actualLogout}}</td>
      <td >{{pd.shiftLogin}}</td>
      <td>
        <i class="far fa-trash-alt fa-lg text-danger" ></i>
      </td>
    </tr>

Save the result in some variable 将结果保存在一些变量中

example

this.http.post('http://localhost:5000/api/DataCorrection/DataCorrection', this.form.value)
    .toPromise()
    .then(res => {
      result = res;
      console.log('Res ' + res);
    });

And try displaying in UI 并尝试在UI中显示

example

<div>{{result|json}}</div>

This will display result in json format 这将以json格式显示结果

Note: use ngFor to display result in table based of your output format 注意:使用ngFor根据您的输出格式在表中显示结果

You are doing a cross domain request because your api and Angular app are being served on different ports. 您正在执行跨域请求,因为您的api和Angular应用正在不同的端口上提供服务。 You can either add a cors header to accept all domains on your api (not recommended) or you can setup a proxy.config.json file so that your api calls are redirected to the same port as your Angular app. 您可以添加cors标头以接受api上的所有域(不建议使用),也可以设置proxy.config.json文件,以便将api调用重定向到与Angular应用程序相同的端口。

{
  "/api/*": {
    "target": "http://localhost:5000/api/",
    "pathRewrite": {
      "^/api": ""
    },
    "changeOrigin": true,
    "secure": false,
    "logLevel": "debug"
  }
}

And in your Angular use /api/DataCorrection/DataCorrection instead of http://localhost:5000/api/DataCorrection/DataCorrection 并在您的Angular中使用/ api / DataCorrection / DataCorrection而不是http:// localhost:5000 / api / DataCorrection / DataCorrection

Then serve with 然后搭配

ng serve --proxy-config proxy.config.json ng serve --proxy-config proxy.config.json

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM