简体   繁体   中英

Can't call controller from angular component

I'm trying Angular with.Net Core and I get trouble calling api controller from my components:

I called my controller with Postman with fake data return to check wether it's my app or my controller and everything is ok with my controller, so the problem lays in my app.

I spent many hours on this trying many things (creating another "service" component or using httpclient straight in my component, in the constructor, in ngInit, outside both, etc etc....) and now I'm really stuck... On all httpClient examples I can find, nothing tell me my call si wrong so I don't understand...

When I try to debug (source explorer on chrome) I can reach the httpClient call, the url is good (same as postman) but then it's the black box, only anonymous functions but I can see my "userlist" is still undefined after the http.get().subsrcibe();

startup.cs


        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });

            services.RegisterServiceServices();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
        {
            app.UseExceptionHandler("/default");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            if (!env.IsDevelopment())
            {
                app.UseSpaStaticFiles();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller}/{action=Index}/{id?}");
            });

            app.UseSpa(spa =>
            {
                // To learn more about options for serving an Angular SPA from ASP.NET Core,
                // see https://go.microsoft.com/fwlink/?linkid=864501

                spa.Options.SourcePath = "ClientApp";

                if (env.IsDevelopment())
                {
                    spa.UseAngularCliServer(npmScript: "start");
                }
            });

            loggerFactory.AddFile("logs/Log_" + DateTime.Today.ToString()+".txt");
        }

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { RouterModule } from '@angular/router';

import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { FooterComponent } from './footer/footer.component';
import { HomeComponent } from './content/home/home.component';

@NgModule({
    declarations: [
        AppComponent,
        HeaderComponent,
        FooterComponent,
        HomeComponent
    ],
    imports: [
        BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
        HttpClientModule,
        FormsModule,
        ReactiveFormsModule,
        RouterModule.forRoot([
            { path: '', component: HomeComponent, pathMatch: 'full' },
            { path: 'home', component: HomeComponent },
        ])
    ],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule { }

home.component.ts

import { Component, Injectable } from '@angular/core';
import { user } from '../../../model/test/user';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';

@Component({
    selector: 'home',
    templateUrl: './home.component.html',
})
@Injectable()
export class HomeComponent {

    public userlist: user[];
    constructor(private httpClient: HttpClient) {
        var base_url: string = window.location.origin;
        var controller: string = base_url + "/svc/Test/GetUserList";
        var userlistresult = this.httpClient.get<user[]>(controller).subscribe((data: any[]) => {
            console.log(data);
            this.userlist = data;
        });
    }
}

user.ts //used the same case as the.cs class to be sure that's not the reason

export interface user {
    UserName: string;
    FirstName: string;
    LastName: string;
}

TestController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Business.Interfaces;
using Newtonsoft.Json;
using Models.Test;
using Microsoft.AspNetCore.Mvc;

namespace AnguTest.Controllers
{
    [ApiController]
    [Route("svc/Test")]
    public class TestController : ControllerBase
    {
        #region Attributes
        private ITestService TestService;
        #endregion

        #region Constructor
        public TestController(ITestService testService)
        {
            TestService = testService;
        }
        #endregion

        #region Methods
        [HttpGet]
        [Route("GetUserList")]
        public JsonResult GetUserList()
        {
            User[] totos = new User[]
            {
                new User(){UserName = "toto1", FirstName = "tata1", LastName = "titi1"},
                new User(){UserName = "toto2", FirstName = "tata2", LastName = "titi2"},
                new User(){UserName = "toto3", FirstName = "tata3", LastName = "titi3"}
            };
            return new JsonResult(totos);
            //return new JsonResult(TestService.GetUserList());
        }
        #endregion
    }
}

Any help is welcome:)

Have you tried to look in the "Network" tab of Chrome (F12) to see what's happening with the request?

Does your code reach console.log(data) ???

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