Búsqueda de sitios web

c# - El método Get no devuelve valor cuando el controlador está en otro proyecto


El problema es que no puedo obtener mis pruebas en la capa de Presentación, y mi controlador está ubicado en la capa de API.

Mi TestController en la capa de API.

    [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());
        }
    }

Mis configuraciones de lanzamiento en la capa 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"
      }
    }
  }
}

Todo lo que está abajo está en una capa de presentación.

Mi servicio de datos

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);
    }
}

Mi app.component

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");
        }
    }
}

Mi 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>

Mi configuración de lanzamiento en la capa de presentación.

{
  "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"
      }
    }
  }
}

Cuando compilo el proyecto, no obtengo pruebas en app.component.html y obtengo "sas" en mi consola, porque las pruebas son nulas, pero cuando voy a localhost:xxxx/api/tests obtengo mis pruebas en json.

Respuesta #1

Debido a que la solicitud HTTP es una solicitud asincrónica, intenta poner la parte if en la función subscribe

loadProducts() {
    this.dataService.getTests()
        .subscribe((data: Test[]) => {
           this.tests = data;

           if (this.tests == null) {
              console.log("sas");
           }

        });     
}

Sin esto, tu if funcionará antes de la respuesta de la solicitud.

Respuesta #2

Necesitas poner tu operador if dentro del callback de subscribe:

loadProducts(): void {
    this.dataService.getTests()
        .subscribe((data: Test[]) => {
            this.tests = data;

            if (this.tests) {
                console.log("Logged");
            }

        });
}