我正在尝试使用.Net Core进行Angular操作,但在从组件调用api控制器时遇到麻烦:
我用带有虚假数据的Postman打电话给我的控制器,以检查它是我的应用程序还是控制器,并且控制器一切正常,所以问题出在我的应用程序上。
我花了很多时间在尝试许多事情上(创建另一个“服务”组件或在组件中,构造函数中,ngInit中,两个外部都直接使用httpclient等),现在我真的卡住了...在我能找到的所有httpClient示例上,什么都没有告诉我我的呼叫错了,所以我听不懂...
当我尝试调试(chrome上的资源管理器)时,我可以到达httpClient调用,URL很好(与邮递员相同),但是它是黑匣子,只有匿名函数,但是我仍然可以看到“用户列表”在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 //使用与.cs类相同的大小写,以确保不是原因
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
}
}
欢迎任何帮助:)