简体   繁体   中英

Calling GET ASP .NET core 2.1 Web API from Angular 6+ client application doesn't return any data

I have created a get web API that returns a single object.When I call that API by typing URL in the browser this displays data in the JSON format on browser window as expected.But when I call the same API from my angular application the data is undefined.Can someone help what is wrong with my code?

I have tried calling web API from my angular application that returns array of strings.I am not receiving even strings in my angular app.

app.component.html

<div style="text-align:center" class="container mt-2">
    <button (click)="search()">test</button>
    <ul>
        <li *ngFor="let item of Candidate">
        <h1>{{item.Name}}</h1>
        </li>
    </ul>   
</div>

app.component.ts

import { Component, OnInit } from '@angular/core';
import { CandidateServicesService } from './candidate-services.service';
import { Candidate } from './core/models/Candidate.mode';

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css']
})
export class AppComponent {
    candidate: Candidate[];
    constructor(private service: CandidateServicesService) { }
    search():void {
        this.service.getCandidateByPosId(101)
        .subscribe((data) => {
                this.candidate = data;
        });
    }
}

candidate-services.services.ts

import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs";
import { Candidate } from "./core/models/Candidate.mode";
@Injectable({
  providedIn: "root"
})
export class CandidateServicesService {
  constructor(private httpClient: HttpClient) {}

  baseUrl: string = "http://localhost:44370/api/Candidate";

  getCandidateByPosId(posId: number): Observable<Candidate> {
    return this.httpClient.get<Candidate>(this.baseUrl + "/" + posId);
  }
}

candidate.mode.ts(Candidate model class)

export class Candidate {
  candidateId: number;
  name: string;
  email: string;
  phone: string;
  skills: string;
}

asp .net core Web Api

//Displays "Unknown error"at angular side.


[HttpGet ("{id}")]
public IActionResult<Candidate> GetBestCandidate (int id) {
    Candidate candidate = new Candidate {
        CandidateId = 1, Name = "John Smith",
            Email = "John.smith@gmail.com",
            Phone = "987654321", Skills = "test"
    }
    return candidate;
}

你应该用

    return Ok(candidate);

Returning something of type ActionResult (as is the case here), requires providing the correct status code with your data.

The most common status code you'll use is 200 OK and 403 Unathorized (possibly 404 Not found too). While you're focused on the data for your client, the framework you're using (.NET Core), sees it as a secondary content, whereas the main part is clarity on how it went.

So, providing the data and explaining that the operation went as supposed to would be achieved by

public ActionResult(...)
{ ...
  return Ok(someData);
}

while telling that something went wrong will be done by

public ActionResult(...)
{ ...
  return NotFound(someData);
}

In the service of your component in Angular, you'll subscribe to the operation and receive two different objects depending on what outcome that has been reported.

...
this.httpClient.get(...)
  .subscribe(
    success => console.log(success),
    error => console.log(error)
  );

Also, to be perfectly sure, I'd break-point the controller process and see what's being returned to avoid stupid cases where the "error" is that you do everything right but the name of a customer actually is null undefined because of some test data jerking around.

问题可能在于您为Web API启用了https ,因此请使用https更改baseUrl

baseUrl: string = "https://localhost:44370/api/Candidate";

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