0

So here is my backend .csproj. Im doing a front end spa in angular connecting to my backend in memory database. I can connect to my database from the URL of my back end application like in the image. Also i can make postman requests and get postman sucessfull responses with this header... so far so good. in my front end there is a problem. i have my front end angular service package with the url i use in postman. in my component i call this method to connect to my service. somehow i cant get the list of "trips" that i get when i do a get request in postman. I am almost 80% sure the error is in backend because i can get requests in other backend applications. So im gonna put my backend code here.

my program.cs

public class Program
{
    public static void Main(string[] args)
    {
        var host = CreateHostBuilder(args).Build();

        using (var scope = host.Services.CreateScope())
        using (var context = scope.ServiceProvider.GetService<AppDbContext>())
        {
            context.Database.EnsureCreated();
        }

        host.Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

launchSettings.json

my startup.cs

public class Startup
{
    public IConfiguration Configuration { get; }

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMemoryCache();


        services.AddControllers().ConfigureApiBehaviorOptions(options =>
        {


        });

        services.AddDbContext<AppDbContext>(options =>
        {
            options.UseInMemoryDatabase(Configuration.GetConnectionString("memory"));
        });


        services.AddScoped<ITripRepository, TripRepository>();
        services.AddScoped<ITripService, TripService>();
        services.AddScoped<IUnitOfWork, UnitOfWork>();
        services.AddAutoMapper(typeof(Startup));


    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }


        app.UseRouting();

        app.UseAuthorization();

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

}

my get controller:

[HttpGet]
    [ProducesResponseType(typeof(List<TripDTO>), 200)]
    public async Task<IEnumerable<TripDTO>> GetAllAsync()
    {
        var trips = await _tripService.ListAsync();
        var dtos = _mapper.Map<IEnumerable<Trip>, IEnumerable<TripDTO>>(trips);

        return dtos;
    }

EDIT: The error im getting when i do a front end console.log in the list im trying to get is this enter image description here

EDIT2: AppDbContext backend

public class AppDbContext : DbContext
{
    public DbSet<Trip> Trips { get; set; }
   

    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        
        builder.Entity<Trip>().ToTable("Trips");
        builder.Entity<Trip>().HasKey(p => p.Id);
        builder.Entity<Trip>().Property(p => p.Id).IsRequired().ValueGeneratedOnAdd();
        builder.Entity<Trip>().Property(p => p.Key).IsRequired().HasMaxLength(10);
        builder.Entity<Trip>().Property(p => p.IsEmpty).IsRequired();
        builder.Entity<Trip>().Property(p => p.Orientation).IsRequired();
        builder.Entity<Trip>().Property(p => p.LineKey).IsRequired().HasMaxLength(10);
        builder.Entity<Trip>().Property(p => p.PathKey).IsRequired().HasMaxLength(10);
        builder.Entity<Trip>().Property(p => p.IsGenerated).IsRequired();
        builder.Entity<Trip>().Property(p => p.PassingTimes)
        .HasConversion(
        v => JsonConvert.SerializeObject(v),
         v => JsonConvert.DeserializeObject<List<PassingTime>>(v));

        builder.Entity<Trip>().HasData
        (
            new Trip { Id = 100,Key="Trip:344",IsEmpty=false,Orientation=false,LineKey="Line:444",PathKey="Path:344",IsGenerated=true }, // Id set manually due to in-memory provider
            new Trip { Id = 1200,Key="Trip:1344",IsEmpty=false,Orientation=false,LineKey="Line:2444",PathKey="Path:3424",IsGenerated=true }
        );

   
    }
}

}

EDIT 3:

HTML 
    <!DOCTYPE html>
<html>

<body>
  <h4>List of Trips</h4>
  <div class="list row">
    <div class="col-md-6">
      <ul class="list-group">
        <li class="list-group-item" *ngFor="let trip of trips; let i = index" [class.active]="i == currentIndex" (click)="setActiveTrip(trip, i)">
          {{ trip.key }}
        </li>
      </ul>
    </div>
    <div *ngIf="!currentTrip">
      <br />
      <p>Please click on a trip to see the details...</p>
    </div>
    <div class="col-md-6">
      <div *ngIf="currentTrip">
        <h4>Selected Trip Details</h4>
        <div>
            <div>
              <label><strong>Key:</strong></label> {{ currentTrip.key }}
            </div>
            
        </div>
      </div>
    </div>
  </div>
</body>

</html>

component.cs

    import { Component, OnInit } from '@angular/core';
import { TripService } from 'src/app/masterdataviagem/services/trip-service';

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

  trips: any;
  currentTrip: any = null;
  currentIndex = -1;
  key = '';
  tripsList:any;

  constructor(private tripService:TripService) { this.tripsList=this.tripService.getAll()}

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

  retrieveTrips() {
   this.trips= this.tripService.getAll().subscribe(
    data => {
      this.trips = data;
      console.log(data);
    },
    error => {
      console.log(error);
    });
   console.log(this.trips);
  }

  refreshList() {
    this.retrieveTrips();
    this.currentTrip = null;
    this.currentIndex = -1;
  }

  setActiveTrip(trip: any, index: number) {
    this.currentTrip = trip;
    this.currentIndex = index;
  }


}
9
  • 2
    "I am almost 80% sure the error is in backend because i can get requests in other backend applications." Wouldn't that actually imply the opposite, that the backend is actually working correctly? Either way, it's virtually impossible to troubleshoot client/server communication when you only show the code for one half of the communication.
    – Claies
    Commented Dec 22, 2020 at 20:23
  • 2
    you didn't mention what error you're getting Commented Dec 22, 2020 at 20:24
  • i already edited the error im getting. sorry... Claies, in this project i did a backend in node.js and express and i can route between angular and backend without any problems. in this project i did an asp.net core backend and its almost the same thing in terms of routing i suppose. if im doing a request sucessfull in postman shouldnt i get it right when i try to route in angular services? im gonna edit in some minutes with more sample codes of my backend code Commented Dec 22, 2020 at 20:31
  • Well without seeing most of the front end code it's not really clear what is going on, but your error from the screenshot cannot find a differ supporting object implies that you are expecting to receive an array of items from the server but are instead receiving a single object. Perhaps you aren't deserializing the JSON?
    – Claies
    Commented Dec 22, 2020 at 20:39
  • Claies somehow im new in this kinda of stuff. im doing a university project and i am approaching this issues just now. so desializing is convert Json data into .NET objects. but where i do that? im suppose to do that in my AppDbContext? im gonna put a print of my AppDbContext too if that helps. im gonna edit now Commented Dec 22, 2020 at 20:47

1 Answer 1

0

Maybe you have to enable CORS in your backend (My guess is the "Unknow Error" at the end of the browser console, thats your console.log(error)).

You can try to use this chrome extension to test: https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf?hl=en.

If your backend response appears with the extension enabled, then you have to enable CORS:

https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#ecors

1
  • this solved my question. thank u very much!! Commented Dec 23, 2020 at 14:26

Not the answer you're looking for? Browse other questions tagged or ask your own question.