【问题标题】:Read Data from Asp.net Core to Angular 7从 Asp.net Core 读取数据到 Angular 7
【发布时间】:2019-04-03 13:58:17
【问题描述】:

早安,

我一直在 Angular 7 和 Asp.net core web api 中进行一些自学。

现在我想从 asp.net core 读取结果并在 Angular 7 中显示。

这是来自 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;
            }
        }

方法GetDateRange返回DataCorrection Model的List

这是我的角度代码

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

}

这是 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>

现在我怎样才能正确阅读它,以便我可以将它加载到表格中。

使用上面的代码。它甚至不填充表格。但它调用console.log

我已经尝试了几个小时寻找解决方案。但我迷路了。我不明白教程,我不能让它工作。

这是来自我的 web api 的响应。我从 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"}

这个数据就是我想在表格中填充的数据

谢谢。

【问题讨论】:

  • AngularJs 标签适用于 Angular 1.X
  • 添加您从后端获得的响应json,以便正确理解您的需求。
  • @ganesh045 你好。我更新了问题。我不明白 json 响应。所以我所做的是我粘贴了我从 web api 获得的响应。我使用 Chrome 网络浏览器阅读了回复

标签: angular asp.net-web-api asp.net-core


【解决方案1】:

我认为这不是问题,

您的模板中有拼写错误,pd.ActualLogin,但实际上在 JSON 响应中拼写为 actualLogin。将您的模板更改为

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

【讨论】:

    【解决方案2】:

    将结果保存在某个变量中

    例子

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

    并尝试在 UI 中显示

    例子

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

    这将以json格式显示结果

    注意:使用 ngFor 根据您的输出格式在表格中显示结果

    【讨论】:

    • 他将收到一个 cors 错误,因为 api 与 Angular 应用程序位于不同的端口上。这对他一点帮助都没有。
    • 在我的应用程序中启用了 cors。我更新了问题。请帮助我。谢谢
    • @AdrianBrand 当我回答这个问题时,他没有提到 CORS
    【解决方案3】:

    您正在执行跨域请求,因为您的 api 和 Angular 应用程序在不同的端口上提供服务。您可以添加一个 cors 标头以接受您的 api 上的所有域(不推荐),或者您可以设置一个 proxy.config.json 文件,以便您的 api 调用被重定向到与您的 Angular 应用程序相同的端口。

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

    并且在您的 Angular 中使用 /api/DataCorrection/DataCorrection 而不是 http://localhost:5000/api/DataCorrection/DataCorrection

    然后配菜

    ng 服务 --proxy-config proxy.config.json

    【讨论】:

    • 我的应用程序中启用了 cors。但是我如何读取来自我的 asp.net 核心的数据?我更新了我的问题。谢谢
    猜你喜欢
    • 2019-08-23
    • 2019-06-27
    • 1970-01-01
    • 2019-08-22
    • 1970-01-01
    • 2020-06-14
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    相关资源
    最近更新 更多