c# - 当控制器在另一个项目中时,Get 方法不返回值
问题是我无法在表示层获取我的测试,而我的控制器位于 API 层。
我在 API 层的 TestController。
[Route("api/[controller]")]
[ApiController]
public class TestsController : ControllerBase
{
private readonly ITestService _testService;
IMapper mapper = new MapperConfiguration(cfg => cfg.CreateMap<TestDTO, TestModel>()).CreateMapper();
public TestsController(ITestService testService)
{
_testService = testService;
}
// GET: api/Tests
[HttpGet]
public IEnumerable<TestModel> GetTests()
{
return mapper.Map<IEnumerable<TestDTO>, IEnumerable<TestModel>>(_testService.GetAllTests());
}
}
我在 API 层的启动设置。
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:58733",
"sslPort": 44340
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "api/tests",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"KTS.WEBAPI": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "api/tests",
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
以下所有内容都位于演示层。
我的数据服务
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Test } from './test';
@Injectable()
export class DataService {//experimental decorations
private url = "api/tests";
constructor(private http: HttpClient) {
}
getTests() {
return this.http.get(this.url);
}
}
我的应用组件
import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';
import { Test } from './test';
@Component({
selector: 'app',
templateUrl: './app.component.html',
providers: [DataService]
})
export class AppComponent implements OnInit {
//test: Test = new Test(); // изменяемый товар
tests: Test[]; // массив товаров
constructor(private dataService: DataService) { }
ngOnInit() {
this.loadProducts(); // загрузка данных при старте компонента
}
// получаем данные через сервис
loadProducts() {
this.dataService.getTests()
.subscribe((data: Test[]) => this.tests = data);
if (this.tests == null) {
console.log("sas");
}
}
}
我的 app.component.html
<h1>Список тестов</h1>
<table class="table table-striped">
<thead>
<tr>
<td>Test</td>
<td>Description</td>
<td>Score</td>
<td>Time</td>
</tr>
</thead>
<tbody>
<tr *ngFor="let t of tests">
<td>{{t?.Title}}</td>
<td>{{t?.Description}}</td>
<td>{{t?.MaxScore}}</td>
<td>{{t?.MaxTime}}</td>
</tr>
</tbody>
</table>
我在演示层的启动设置。
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:64165",
"sslPort": 44368
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"KTS.PL": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
当我编译项目时,我在 app.component.html 中没有得到测试,并且在控制台中得到 "sas",因为测试为 null,但当我访问 localhost:xxxx/api/tests 时,我在 json 中得到了我的测试。
答案#1
因为HTTP请求是异步请求,尝试将if部分放在subscribe函数中
loadProducts() {
this.dataService.getTests()
.subscribe((data: Test[]) => {
this.tests = data;
if (this.tests == null) {
console.log("sas");
}
});
}
没有这个,你的if将在请求响应之前执行。
答案#2
你需要将你的 if 操作符放在 subscribe 回调中:
loadProducts(): void {
this.dataService.getTests()
.subscribe((data: Test[]) => {
this.tests = data;
if (this.tests) {
console.log("Logged");
}
});
}
