【发布时间】:2019-05-18 10:04:39
【问题描述】:
我创建了一个返回单个对象的获取 Web API。当我通过在浏览器中键入 URL 调用该 API 时,这会按预期在浏览器窗口上以 JSON 格式显示数据。但是当我从我的角度调用相同的 API 时应用程序数据未定义。有人可以帮助我的代码有什么问题吗?
我尝试从返回字符串数组的 Angular 应用程序调用 Web API。我在 Angular 应用程序中甚至没有收到字符串。
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(候选模型类)
export class Candidate {
candidateId: number;
name: string;
email: string;
phone: string;
skills: string;
}
asp .net core Web API
//在角度侧显示“未知错误”。
[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;
}
【问题讨论】:
-
getCandidateByPosId(posId: number) { return this.httpClient.get(this.baseUrl + "/" + posId); } 试试这个。
标签: angular asp.net-core-webapi