Метод Get не возвращает значение, когда контроллер находится в другом проекте. - PullRequest
1 голос
/ 20 апреля 2020

Проблема в том, что я не могу получить свои тесты на уровне презентации, а мой контроллер находится на уровне API.

Мой TestController на уровне 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());
        }
    }

Мои настройки запуска в слое 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"
      }
    }
  }
}

Все ниже находится в слое презентации.

Мой data.service

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

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

Мой 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" в моей консоли, потому что тесты нулевые, но когда я go на localhost: xxxx / api / tests, я получаю свои тесты в json.

Ответы [ 2 ]

5 голосов
/ 20 апреля 2020

Поскольку запрос HTTP является асинхронным запросом, попробуйте поместить часть if в функцию subscribe

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

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

        });     
}

. Без этого ваш if будет работать до ответа запрос.

1 голос
/ 24 апреля 2020

Вы должны поместить свой оператор if внутри subscribe обратного вызова:

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

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

        });
}
...