[英]How to get data from local Web API (ASP.NET Core) in Angular
這是我生成數據以創建 Treeview 時的代碼:
import { Injectable } from '@angular/core';
export class Product {
id: string;
text: string;
expanded?: boolean;
items?: Product[];
price?: number;
image?: string;
}
我在 Angular 中創建了這樣的數據:
var products: Product[] = [{
id: "1",
text: "Stores",
expanded: true,
items: [{
id: "1_1",
text: "Super Mart of the West",
expanded: true,
items: [{
id: "1_1_1",
text: "Video Players",
items: [{
id: "1_1_1_1",
text: "HD Video Player",
price: 220,
image: "images/products/1.png"
}, {
id: "1_1_1_2",
text: "SuperHD Video Player",
image: "images/products/2.png",
price: 270
}]
}, {
id: "1_1_2",
text: "Televisions",
expanded: true,
items: [{
id: "1_1_2_1",
text: "SuperLCD 42",
image: "images/products/7.png",
price: 1200
}, {
id: "1_1_2_2",
text: "SuperLED 42",
image: "images/products/5.png",
price: 1450
}
...
}]
}
這是我在 Angular 中運行的 output:
而且我不想用這種方式來設置數據。 我可以通過從本地主機 web API(從 ASP.NET 核心創建)獲取數據嗎?
感謝你的幫助。 我只是一個使用 Angular 的新手(如果我的問題很愚蠢,請原諒我)!!
我不想用這種方式來設置數據。 我可以通過從本地主機 web API(從 ASP.NET 核心創建)獲取數據嗎?
如果您想從您的 Angular 前端向您的 API 后端發出 http 請求以獲取數據,如評論中提到的@DM,您可以嘗試使用 HttpClient。
注入 HttpClient 服務
import { HttpClient } from '@angular/common/http';
發出 http 請求
products: Product[];
GetProducts() {
this.http.get<Product[]>('https://localhost:44386/api/nodeitems')
.subscribe(data => {
this.products = data;
});
}
此外,您可能需要在 API 后端應用程序上啟用 CORS 以設置允許的來源。
https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-5.0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.