简体   繁体   中英

HttpRequest problem with Angular and .Net

I have problem with http response. And i have no idea what is the problem. Could somebody help me pls? ts file:

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

shared service:

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

My Repository

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

Model(In BaseEntity is field "id")

using System.ComponentModel.DataAnnotations;

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

Everything works in Postman and values exists in database. I just checked GET-method and it isn't working. Iit's error in Angular and undefined return value photo of Error in Debug

The error may be due to calling the backend API from a port different from the one that your Angular app runs on. you may need to enable CORS in your ASP.NET project first to allowing calling APIs from another domain or different port numbers.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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