繁体   English   中英

Angular和.Net的HttpRequest问题

[英]HttpRequest problem with Angular and .Net

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

Controller:

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 方法,但它不起作用。 Iit 是 Angular 中的错误和Debug 中的错误的未定义返回值照片

该错误可能是由于从与运行 Angular 应用程序的端口不同的端口调用后端 API 所致。 您可能需要首先在您的 ASP.NET 项目中启用 CORS 以允许从另一个域或不同的端口号调用 API。

if you are using ASP.NET Core, install this package Microsoft.AspNetCore.Cors and configure it in your Startup.cs Check this Answer Configure CORS in your ASP.NET project

暂无
暂无

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

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