简体   繁体   中英

How to get data from local Web API (ASP.NET Core) in Angular

Here is my code when I generate the data to create the Treeview:

import { Injectable } from '@angular/core';
export class Product {
     id: string;
     text: string;
     expanded?: boolean;
     items?: Product[];
     price?: number;
     image?: string;
}

I created data in Angular like this:

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              
        }
            ...
        }]
    }

This is my output run in Angular:

角度输出

And I don't want to use this way to set data. Can I get data by getting it from the localhost web API (created from ASP.NET Core)?

本地 WEB API (Swagger UI - ASP.NET Core)

Thanks for all your help. I'm just a novice working with Angular (forgive me if my question is silly)!!

I don't want to use this way to set data. Can I get data by getting it from the localhost web API (created from ASP.NET Core)?

If you'd like to make http request(s) from your Angular frontend to your APIs backend to get data, as @DM mentioned in comment, you can try to use HttpClient.

inject the HttpClient service

import { HttpClient } from '@angular/common/http';

make http request(s)

products: Product[];

GetProducts() {
    this.http.get<Product[]>('https://localhost:44386/api/nodeitems')
    .subscribe(data => {
      this.products = data;
    });
}

Besides, you may need to enable CORS on APIs backend app to set the allowed origins.

https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-5.0

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