簡體   English   中英

如何從數據庫中獲取數據到表中(Angular 8、C#、WebApi)

[英]How to get data from database into a table (Angular 8, C#, WebApi)

我正在嘗試做一些相對簡單的事情,但我對所有選項感到困惑,我需要你的幫助。

我正在嘗試從數據庫中檢索信息,將其通過 API 並將其顯示在我在 Angular 中創建的表中。 這個想法是將所有狀態為 1 的生產力放入某個列表中。 將列表返回到 Angular 並在表格中顯示數據。

我知道有很多選擇。 誠然,我測試的所有示例都在 Angular 和 C # 項目中。 但是每個項目都彼此不同,沒有一個例子與我的項目結構相匹配。

這就是我的代碼:(我知道很多細節都丟失了,而且並不完美,所以我需要幫助)

messages.component.html

<table id="customers">
                    <tr>
                        <th>productivity num</th>
                        <th>user ID</th>
                        <th>amount</th>
                        <th>Special comments</th>
                        <th>Accept/reject</th>
                    </tr>
                    <tr *ngFor="let item of productivityList">
                        <td>{{item.ProductivyCode}}</td>
                        <td>{{item.UserCode}}</td>
                        <td>{{item.ProductivityNum}}</td>
                        <td>{{item.Cmment}}</td>
                        <td>
                            <div>
                                <button class="button is-success">accept</button>
                                <button class="button is-danger">reject</button>
                            </div>
                        </td>
                    </tr>
                </table>

消息.component.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { UserService } from 'src/app/shared/services/user.service';
import { Productivity } from 'src/app/shared/models/productivity';

@Component({
  selector: 'app-messages',
  templateUrl: './messages.component.html',
  styleUrls: ['./messages.component.css']
})
export class MessagesComponent implements OnInit {

  constructor(private router: Router, private userservice: UserService) { }

  productivityList: Productivity[];

  ngOnInit():void {
   this.getProductivityRequest();
  }

  getProductivityRequest() {
    this.userservice.getProductivityRequest().subscribe((res) => {
      this.productivityList = res;
      if (res)
        console.log("ok")
    },
      err =>
        console.log("faild")
    );
  }

用戶服務.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http'
import { Observable, observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { User } from '../models/user.model';
import { Productivity } from '../models/productivity';
import { Time } from '@angular/common';
import { stringify } from 'querystring';
//import { read } from 'fs';



@Injectable({
  providedIn: 'root'
})
export class UserService {

  url: string = "https://localhost:44387/api/User/";
  productivityList: Productivity[];

  constructor(private http: HttpClient) { }

  getProductivityRequest() {
    return this.http.get(this.url+'getProductivityRequest');
}

UserController.cs //這是我在 C# 中的項目

using BL;
using DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;

namespace WebApiSystem.Controllers
{
    [EnableCors(origins: "http://localhost:4200", headers: "*", methods: "*", SupportsCredentials = true)]
    [RoutePrefix("api/User")]

    public class UserController : ApiController
    {
        [HttpGet]
        [Route("getProductivityRequest")]

        public IHttpActionResult GetProductivityRequest()
        {
            return Ok(UserService.GetProductivityRequest());
        }    

    }
}

用戶服務.cs

using DAL;
using DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BL
{
    public class UserService
    {
        public static IQueryable<dynamic> GetProductivityRequest()
        {
            using (Model2 db = new Model2())
            {
                db.Configuration.ProxyCreationEnabled = false;
                db.Configuration.LazyLoadingEnabled = false;
                IQueryable<dynamic> PList = db.ProductivityTbl.Select();//I want to make a condition within the SELECT that only an object whose status 1 will enter the list
                return PList;
            }
        }

    }
}

我希望它足夠清楚,也許你可以告訴我如何正確編寫代碼,如果有人有其他想法,比如返回 JSON object 我希望你能告訴我如何做......謝謝!

To resovle the CORS error when calling web api from an Angular front end, you can configure the behaviour in the Configure() method of your Startup class within the web api...

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment()) app.UseDeveloperExceptionPage();

        app.UseCors("AllowAll");

        app.UseStaticFiles();
        app.UseRouting();
        app.UseAuthentication();
        app.UseAuthorization();
    }

我試圖打開一個新項目,但仍然沒有看到上面的文件。 我嘗試手動添加但無法實現接口(他希望我實現一個全新的接口)文件中是否缺少某些代碼?

啟動.cs

using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(WebApiSystem.Startup1))]

namespace WebApiSystem
{
    public class Startup1
    {
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
        }
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment()) app.UseDeveloperExceptionPage();

            app.UseCors("AllowAll");

            app.UseStaticFiles();
            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM