【问题标题】:HttpRequest problem with Angular and .NetAngular 和 .Net 的 HttpRequest 问题
【发布时间】:2021-04-07 02:51:46
【问题描述】:

我的 http 响应有问题。我不知道是什么问题。有人可以帮我吗? ts 文件:

import { Component, OnInit } from '@angular/core';
import {SharedService} from 'src/app/shared.service';

@Component({
  selector: 'app-today',
  templateUrl: './today.component.html',
  styleUrls: ['./today.component.css']
})
export class TodayComponent implements OnInit {

  constructor(private service:SharedService) { }

  TodayList:any=[];

  ngOnInit(): void {
    this.refreshTodayList();
  }

  refreshTodayList(){
    this.service.getTodayList().subscribe(data=>{
      this.TodayList = data;
    })
  }
}

共享服务:

import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http'
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class SharedService {
  readonly APIUrl = 'https://localhost:44336/api';
  constructor(private http:HttpClient) { }

  getTodayList(): Observable<any[]>{
    return this.http.get<any>(this.APIUrl+'/today')
  }

  addToday(val:any){
    return this.http.post(this.APIUrl + '/Today', val)
  }

  updateToday(val:any){
    return this.http.put(this.APIUrl + '/Today', val)
  }

  deleteToday(val:any){
    return this.http.delete(this.APIUrl + '/Today', val)
  }

  getPlannedList(): Observable<any[]>{
    return this.http.get<any>(this.APIUrl + '/planned')
  }

  addPlanned(val:any){
    return this.http.post(this.APIUrl + '/planned', val)
  }

  updatePlanned(val:any){
    return this.http.put(this.APIUrl + '/planned', val)
  }

  deletePlanned(val:any){
    return this.http.delete(this.APIUrl + '/planned', val)
  }
}

html:

<table class="table">  
    <thead>  
      <tr>  
        <td>Employee Codetd </td>
        <td> Nametd </td>
       <td>Department </td>
      <td>Locationt </td>
      </tr> </thead>  
    <tbody>  
      <tr *ngFor="let rec of TodayList">  
        <td>{{rec.record}}</td>  
    </tbody>
<table>  
        

控制器:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using ToDoList.Data;
using ToDoList.Interfaces;
using ToDoList.Models;

namespace ToDoList.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TodayController : ControllerBase
    {
        private readonly IRecordRepository<RecordsToday> repo;

        public TodayController(IRecordRepository<RecordsToday> r)
        {
            repo = r;
        }

        [HttpGet]
        public IActionResult GetAllRecords()
        {
            var res = repo.GetRecordsList();
            if (res != null)
            {
                return Ok(res);
            }
            return BadRequest("No records");
        }

        [HttpGet]
        [Route("{id}")]
        public IActionResult GetRecordById(int id)
        {
            var res = repo.GetRecord(id);
            if (res != null)
            {
                return Ok(res);
            }
            return BadRequest("Record missing");
        }

        [HttpPost]
        public IActionResult AddRecord(RecordsToday record)
        {
            repo.Create(record);
            return Ok("Record saved");
        }

        [HttpPut]
        public IActionResult UpdateRecord(RecordsToday record)
        {
            repo.Update(record);
            return Ok("Record updated");
        }

        [HttpDelete]
        public IActionResult DeleteRecord(RecordsToday record)
        {
            repo.Delete(record);
            return Ok("Record deleted");
        }
    }
}

我的仓库

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using ToDoList.Interfaces;
using ToDoList.Models;


namespace ToDoList.Data
{
    public class RecordRepository<T> : IRecordRepository<T> where T : BaseEntity
    {
        private readonly RecordDbContext _context;
        private readonly DbSet<T> entity;

        public RecordRepository(RecordDbContext db)
        {
            _context = db;
            entity = _context.Set<T>();
        }

        public void Create(T item)
        {
            if (entity == null)
                throw new ArgumentNullException("item");
            entity.Add(item);
            Save();
        }

        public void Delete(T item)
        {
            if (entity == null)
                throw new ArgumentNullException("item");
            entity.Remove(item);
            Save();
        }

        public T GetRecord(int id)
        {
            return entity.FirstOrDefault(c => c.id == id);
        }

        public IEnumerable<T> GetRecordsList()
        {
            return entity.AsEnumerable();
        }

        public void Save()
        {
            _context.SaveChanges();
        }

        public void Update(T item)
        {
            if (entity == null)
                throw new ArgumentNullException("item");
            entity.Update(item);
            Save();
        }
    }
}

模型(在 BaseEntity 中是字段“id”)

using System.ComponentModel.DataAnnotations;

namespace ToDoList.Models
{
    public class RecordsToday : BaseEntity
    {
        [Required]
        public string record { get; set; }
    }
}

一切都在 Postman 中工作,并且值存在于数据库中。我刚刚检查了 GET 方法,但它不起作用。 Angular 中的错误和未定义的返回值 photo of Error in Debug

【问题讨论】:

    标签: c# angular http asp.net-web-api


    【解决方案1】:

    该错误可能是由于从与运行 Angular 应用程序的端口不同的端口调用后端 API 造成的。您可能需要先在 ASP.NET 项目中启用 CORS,才能允许从其他域或不同端口号调用 API。

    如果您使用的是 ASP.NET Core,请安装此软件包 Microsoft.AspNetCore.Cors 并在您的 Startup.cs 中进行配置 检查这个答案 Configure CORS in your ASP.NET project

    【讨论】:

    • 在我的应用程序中添加了 Cors。还是行不通。同样的问题。我认为这是 Angular 的问题。还在 ConfigureServices 中添加了 services.AddMvc(options => options.EnableEndpointRouting = false)。没有这个我不能使用 CORS
    猜你喜欢
    • 2021-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-21
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    相关资源
    最近更新 更多