c# - Angular 4 - 如何從 ASP.Net Web API 獲取資料
使用著名的 Visual Studio 2017 Angular 4 模板,我測試了側邊導航欄按鈕,並能夠獲取內存中的數據。
然後我在專案中新增了一個使用 Entity Framework 連接資料庫的 ASP.Net Core 2.0 API 控制器,並讓它以 200 HTTP GET 結果運行。
控制器程式碼:
#region TodoController
namespace TodoAngularUI.Controllers
{
[Route("api/[controller]")]
public class TodoController : Controller
{
private readonly SchoolContext _context;
#endregion
public TodoController(SchoolContext DbContext)
{
_context = DbContext;
if (_context.Todo.Count() == 0)
{
_context.Todo.Add(new Todo { TaskName = "Item1" });
_context.SaveChanges();
}
}
#region snippet_GetAll
[HttpGet]
public IEnumerable<Todo> GetAll()
{
return _context.Todo.ToList();
}
[HttpGet("{id}", Name = "GetTodo")]
public IActionResult GetById(long id)
{
var item = _context.Todo.FirstOrDefault(t => t.Id == id);
if (item == null)
{
return NotFound();
}
return new ObjectResult(item);
}
#endregion
現在,我想使用 Angular 顯示產生的 ASP.Net Core 控制器資料,所以我創建了一個名為「todo」的 TypeScript 元件,如下所示:
import { Component, Inject } from '@angular/core';
import { Http } from '@angular/http';
@Component({
selector: 'todo',
templateUrl: './todo.component.html'
})
export class TodoComponent {
public Todo: task[];
constructor(http: Http, @Inject('BASE_URL') baseUrl: string) {
http.get(baseUrl + '/api/todo').subscribe(result => {
this.Todo = result.json() as task[];
}, error => console.error(error));
}
}
interface task {
Id: number;
TaskName: string;
IsComplete: boolean;
}
並創建了其 HTML 組件如下:
<h1>Todo tasks</h1>
<p>This component demonstrates fetching Todo tasks from the server.</p>
<p *ngIf="!todo"><em>Loading...</em></p>
<table class='table' *ngIf="Todo">
<thead>
<tr>
<th>Id</th>
<th>Task Name</th>
<th>Is complete</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let Task of todo">
<td>{{ Task.Id }}</td>
<td>{{ Task.TaskName }}</td>
<td>{{ Task.Iscomplete }}</td>
</tr>
</tbody>
</table>
然後去在導航側邊欄菜單中添加它的路由,這裡是 TypeScript 代碼:
import { Component } from '@angular/core';
@Component({
selector: 'nav-menu',
templateUrl: './navmenu.component.html',
styleUrls: ['./navmenu.component.css']
})
export class NavMenuComponent {
}
這裡是導航欄的 HTML 代碼:
<div class='main-nav'>
<div class='navbar navbar-inverse'>
<div class='navbar-header'>
<button type='button' class='navbar-toggle' data-toggle='collapse' data-target='.navbar-collapse'>
<span class='sr-only'>Toggle navigation</span>
<span class='icon-bar'></span>
<span class='icon-bar'></span>
<span class='icon-bar'></span>
<span class='icon-bar'></span>
</button>
<a class='navbar-brand' [routerLink]="['/home']">TodoAngularUI</a>
</div>
<div class='clearfix'></div>
<div class='navbar-collapse collapse'>
<ul class='nav navbar-nav'>
<li [routerLinkActive]="['link-active']">
<a [routerLink]="['/home']">
<span class='glyphicon glyphicon-home'></span> Home
</a>
</li>
<li [routerLinkActive]="['link-active']">
<a [routerLink]="['/counter']">
<span class='glyphicon glyphicon-education'></span> Counter
</a>
</li>
<li [routerLinkActive]="['link-active']">
<a [routerLink]="['/fetch-data']">
<span class='glyphicon glyphicon-th-list'></span> Fetch data
</a>
</li>
<li [routerLinkActive]="['link-active']">
<a [routerLink]="['/api/todo']">
<span class='glyphicon glyphicon-apple'></span> Todo api
</a>
</li>
</ul>
</div>
</div>
以及我的 app.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
}
這裡的問題是,當我點擊菜單按鈕獲取數據時,什麼也沒有發生,其他按鈕都能正常工作,但這個不行,而且當直接使用瀏覽器 URL 時,仍然顯示 200 結果。
沒有錯誤訊息,我在網路上搜尋與 Angular 中按鈕無法點擊相關的問題,以及從 ASP.Net 傳遞資料到 Angular 相關的問題時,都沒有找到解決方案。
我做錯了什麼?
答案#1
(答案來自我上面的評論)
我以前使用微軟的 Angular 4 範本時也遇到過類似的問題。
問題
微軟在其範本中提供了 BASE_URL 字串——它是透過從 index.cshtml 中的 base 標籤提取 href 屬性獲得的(BASE_URL 字串並非 Angular 框架的一部分)。
index.cshtml 中的 base 標籤應該看起來像 <base href="~/" />
這意味著在你的 Angular 4 專案中,任何使用 BASE_URL 的地方,BASE_URL 已經附加了一個 / 字元。
所以查看這個呼叫 http.get 使用該 URL 的元件:
@Component({
selector: 'todo',
templateUrl: './todo.component.html'
})
export class TodoComponent {
public Todo: task[];
constructor(http: Http, @Inject('BASE_URL') baseUrl: string) {
http.get(baseUrl + '/api/todo').subscribe(result => {
this.Todo = result.json() as task[];
}, error => console.error(error));
}
}
請注意,你對 http.get(baseUrl + '/api/todo') 的呼叫,在 /api/todo 前面有一個 / —— 因此傳入 http.get 的參數會因 BASE_URL 額外的 / 而看起來像 http://example.com//api/todo。
解決方案
試試 http.get(baseUrl + 'api/todo')(注意 api/todo 前面沒有 /)- BASE_URL 字串應該已經包含了這個,如果模板中其他部分沒有被更改的話。
更新 22-03-2018:使用 HTTP POST
根據下面的評論,這裡有一個 POST 的快速範例函數,假設 baseUrl 和 http 都已經被注入到建構函數中:
import { Observable } from 'rxjs/rx';
import { Http, Headers, RequestOptions } from '@angular/http';
@Component({
selector: 'todo',
templateUrl: './todo.component.html'
})
export class TodoComponent {
constructor(private http: Http,
@Inject('BASE_URL') private baseUrl: string) {
}
post(todo: Todo) {
let fullUrl = this.baseUrl + 'api/todo';
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
this.http.post(fullUrl, JSON.stringify(todo), options)
.subscribe(result => {
console.log(result);
}, error => console.error(error));
}
}
在 ASP.NET WebAPI 端(它會隱式地知道如何處理 HTTP POST 請求中 application/json 的 Content-Type):
public class TodoController : Controller
{
[HttpPost]
public IActionResult Post([FromBody] Todo todo)
{
return Ok();
}
}
