Currently, I am working on developing a straightforward notes application using Entity Framework in ASP.Net Core for the backend and AngularJS for the frontend.
The main objective is to have the app load a pre-existing list of notes from my MySQL database upon initialization.
However, upon making a GET request, I encountered an error message as shown below: https://i.sstatic.net/e6hke.png
Prior to this issue, I had dealt with CORS problems by adding http://
to my connection string. After resolving that, this new error appeared, and despite extensive research online, I have not been able to find a solution.
Below is my implementation in note.service.ts
:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Note } from '../note';
@Injectable({
providedIn: 'root'
})
export class NoteService {
private url: string = "http://localhost:44353/api/NotesLists";
constructor(private http: HttpClient) { }
getNotes(): Observable<Note[]> {
return this.http.get<Note[]>(this.url);
}
}
This code snippet shows how the app subscribes and retrieves responses in the home component:
import { Component, OnInit } from '@angular/core';
import { NoteService } from '../services/note.service';
import { Note } from '../note';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
public notes: Note[] = [];
constructor(private noteService: NoteService) { }
ngOnInit(): void {
this.noteService.getNotes()
.subscribe(data => this.notes = data);
}
}
Furthermore, here is the [HttpGet]
request implemented in the .Net Core backend:
[HttpGet]
public IActionResult Get()
{
try
{
var response = _datacontext.NotesList
.Include(notesList => notesList.Note)
.ToList();
if (response.Count == 0)
{
return NotFound();
}
return Ok(response);
}
catch (Exception e)
{
return StatusCode(500, e.Message);
}
}
Lastly, for better contextual understanding, here is the DataContext
utilized in the project:
using Microsoft.EntityFrameworkCore;
using noteAppAPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace noteAppAPI.Helpers
{
public class DataContext : DbContext
{
public DataContext(DbContextOptions<DataContext> option) : base(option)
{
}
public DbSet<NotesList> NotesList { get; set; }
public DbSet<Note> Notes { get; set; }
}
}