Angular with .Net backend. HttpErroResponse

  angular, backend, c#, http-error

I have a problem with recieving data from backend. Here is my code:

Backend in .Net:

Model:

public class TodayModel
    {
        [Required]
        public int id { get; set; }
        [Required]
        public string record { get; set; }
    }

Standart controller with using of Entity Framework:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using ToDo.Data;
using ToDo.Models;

namespace ToDo.Controllers
{
    [Produces("application/json")]
    [Route("api/[controller]")]
    [ApiController]
    public class TodayController : ControllerBase
    {
        private readonly ToDoContext _context;

        public TodayController(ToDoContext context)
        {
            _context = context;
        }

        // GET: api/Today
        [HttpGet]
        public async Task<ActionResult<IEnumerable<TodayModel>>> GetTodayModel()
        {
            return await _context.TodayModel.ToListAsync();
        }

        // GET: api/Today/5
        [HttpGet("{id}")]
        public async Task<ActionResult<TodayModel>> GetTodayModel(int id)
        {
            var todayModel = await _context.TodayModel.FindAsync(id);

            if (todayModel == null)
            {
                return NotFound();
            }

            return todayModel;
        }

        // PUT: api/Today/5
        // To protect from overposting attacks, enable the specific properties you want to bind to, for
        // more details, see https://go.microsoft.com/fwlink/?linkid=2123754.
        [HttpPut("{id}")]
        public async Task<IActionResult> PutTodayModel(int id, TodayModel todayModel)
        {
            if (id != todayModel.id)
            {
                return BadRequest();
            }

            _context.Entry(todayModel).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!TodayModelExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }

        // POST: api/Today
        // To protect from overposting attacks, enable the specific properties you want to bind to, for
        // more details, see https://go.microsoft.com/fwlink/?linkid=2123754.
        [HttpPost]
        public async Task<ActionResult<TodayModel>> PostTodayModel(TodayModel todayModel)
        {
            _context.TodayModel.Add(todayModel);
            await _context.SaveChangesAsync();

            return CreatedAtAction("GetTodayModel", new { id = todayModel.id }, todayModel);
        }

        // DELETE: api/Today/5
        [HttpDelete("{id}")]
        public async Task<ActionResult<TodayModel>> DeleteTodayModel(int id)
        {
            var todayModel = await _context.TodayModel.FindAsync(id);
            if (todayModel == null)
            {
                return NotFound();
            }

            _context.TodayModel.Remove(todayModel);
            await _context.SaveChangesAsync();

            return todayModel;
        }

        private bool TodayModelExists(int id)
        {
            return _context.TodayModel.Any(e => e.id == id);
        }
    }
}

Startup.cs file:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.EntityFrameworkCore;
using ToDo.Data;

namespace ToDo
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddDbContext<ToDoContext>(options =>
                    options.UseSqlServer(Configuration.GetConnectionString("ToDoContext")));       

            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                    builder => builder.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader());
            });

            services.AddMvc(opt => opt.EnableEndpointRouting = false);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            app.UseCors("CorsPolicy");
            app.UseMvc();
        }
    }
}

As you can see, here is CORS and Headers and origins connected. I don’t think, that it’s problem in backend. In database i have one record. Next is Angular:

Service file:

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class ToDoService {

  private headers: HttpHeaders;
  private ApiURL = "http://localhost:58443/api"

  constructor(private http:HttpClient) {
    this.headers = new HttpHeaders({'Content-Type': 'application/json; charset=utf-8'})
   }

   public getToday()
   {
    return this.http.get(this.ApiURL + '/today', {headers: this.headers})
  }

  public addToday(val: any) {
    return this.http.post(this.ApiURL + '/today', val, {headers: this.headers});
  }

  public removeToday(val: any) {
    return this.http.delete(this.ApiURL + '/today/' + val.id, {headers: this.headers});
  }

  public updateToday(val: any) {
    return this.http.put(this.ApiURL + '/today/' + val.id, val, {headers: this.headers});
  }
}

BTW, with Observable inheritance from rxjs it’s still not working.

Component:

import { Component, OnInit } from '@angular/core';
import { ToDoService } from '../to-do.service';

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

  constructor(private service:ToDoService) { }

  TodayList:any=[];

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

  public refreshListToday()
  {
    this.service.getToday().subscribe(data=>{
      this.TodayList = data;
    })
  }
}

And finally html file

<p>Incoming data:</p>
<ul>
    <li *ngFor = "let item of TodayList">{{item.record}}</li>
</ul>

In the end I receive HttpErrorResponse by the debugging.

I would really appreciate some help.

Source: Angular Questions

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.