다음을 사용하여 웹 애플리케이션 구축에 대한 포괄적인 단계별 자습서 ASP.NET 웹 API, Angular 7 및 Microsoft SQL Server. 이 튜토리얼에서는 다음을 사용하여 RESTful API 웹 서비스를 생성합니다. ASP.NET 그런 다음 Core Web API는 Angular 7을 사용하여 프런트 엔드 응용 프로그램을 만듭니다. 백엔드의 경우 추가 데이터베이스 Northwind와 함께 Microsoft SQL Server 2017 Express Edition을 사용합니다. 이것은 우리의 첫 번째 ASP.NET 튜토리얼이므로 많은 결점과 많은 토론이 있을 것입니다.
목차:
- Northwind 샘플 데이터베이스 다운로드 및 설치
- 새 ASP.NET Web API 응용 프로그램 만들기 및 구성
- Microsoft SQL Server 데이터베이스에서 모델 생성
- 요청 본문 및 응답에 대한 DTO(Data Transfer Object) 생성
- 모델 클래스로 DTO 매핑을 위한 도우미 클래스 만들기
- CRUD(Create, Read, Update Delete) 작업을 위한 리포지토리 생성
- CRUD 작업을 위한 컨트롤러 생성
- Postman을 사용한 테스트 API
- Angular 7 CLI 설치 또는 업데이트 및 애플리케이션 생성
- Angular 페이지/컴포넌트 간 탐색 경로 추가
- RESTful API에 접근하기 위한 서비스 생성
- Angular 7 재질을 사용하여 공급업체 목록 표시
- Angular 7 재질을 사용하여 공급업체 세부 정보 표시 및 삭제
- Angular 7 재질을 사용하여 공급업체 추가
- Angular 7 재질을 사용하여 공급업체 편집
- ASP.NET Core Web API 및 Angular 7 CRUD 웹 애플리케이션 실행 및 테스트
이 자습서에는 다음 도구, 프레임워크, 패키지 및 모듈이 필요합니다.
- Northwind 샘플 데이터베이스 다운로드 및 설치
- 새 ASP.NET Web API 응용 프로그램 만들기 및 구성
- Microsoft SQL Server 데이터베이스에서 모델 생성
- 요청 본문 및 응답에 대한 DTO(Data Transfer Object) 생성
- 모델 클래스로 DTO 매핑을 위한 도우미 클래스 만들기
- CRUD(Create, Read, Update Delete) 작업을 위한 리포지토리 생성
- CRUD 작업을 위한 컨트롤러 생성
- Postman을 사용한 테스트 API
- Angular 7 CLI 설치 또는 업데이트 및 애플리케이션 생성
- Angular 페이지/컴포넌트 간 탐색 경로 추가
- RESTful API에 접근하기 위한 서비스 생성
- Angular 7 재질을 사용하여 공급업체 목록 표시
- Angular 7 재질을 사용하여 공급업체 세부 정보 표시 및 삭제
- Angular 7 재질을 사용하여 공급업체 추가
- Angular 7 재질을 사용하여 공급업체 편집
- ASP.NET Core Web API 및 Angular 7 CRUD 웹 애플리케이션 실행 및 테스트
위의 모든 필수 도구를 이미 설치했다고 가정합니다. 이제 DotNet SDK가 이미 설치되어 경로에 추가되었는지 확인해야 합니다. 명령 프롬프트를 연 다음 이 명령을 입력하여 DotNet이 설치되어 있고 명령 프롬프트를 통해 실행할 수 있는지 확인합니다.
dotnet --version
이 결과를 얻을 수 있습니다.
2.1.403
우리는 DotNet Framework SDK 버전 2.1.403을 사용하고 있습니다. 이는 주요 단계로 이동할 준비가 되었음을 의미합니다.
1. Northwind 샘플 데이터베이스 다운로드 및 설치
SQL Server 2017용 Northwind 샘플 데이터베이스를 다운로드하려면 브라우저를 열고 이 링크로 이동하십시오. https://northwinddatabase.codeplex.com/ . 다운로드 후 루트 폴더(예: C:)에 압축을 풉니다. 다음으로 Microsoft SQL Server Management Studio를 엽니다. 로컬 서버에 로그인한 다음 개체 탐색기 창에서 데이터베이스를 마우스 오른쪽 버튼으로 클릭한 다음 데이터베이스 복원을 선택합니다.
장치를 선택한 다음 ... 버튼을 클릭합니다. 장치 선택 대화 상자가 열리고 추가 버튼을 클릭하고 이전에 압축을 푼 .bak 파일을 찾은 다음 확인 버튼을 클릭한 다음 다시 확인 버튼을 클릭합니다.
내 평균 바이러스 백신이 업데이트되지 않습니다
확인 버튼을 클릭하여 Northwind 데이터베이스를 복원합니다. 이제 데이터베이스에 Northwind 데이터베이스가 표시되어야 합니다.
2. 신규 생성 및 구성 ASP.NET 웹 API 애플리케이션
약간 다른 ASP.NET 핵심 응용 프로그램 생성, 우리는 명령 프롬프트를 사용합니다. 물론 Microsoft Visual Studio를 사용할 때 더 쉬운 방법을 사용할 수 있습니다. 명령 프롬프트에서 프로젝트 폴더로 이동한 다음 이 명령을 입력합니다.
dotnet new webapi –o AspNetAngular –n AspNetAngular
명령 프롬프트에서 아래와 같이 출력됩니다.
The template 'ASP.NET Core Web API' was created successfully. Processing post-creation actions... Running 'dotnet restore' on AspNetAngularAspNetAngular.csproj... Restoring packages for C:UsersDIDINProjectsAspNetAngularAspNetAngular.csproj... Generating MSBuild file C:UsersDIDINProjectsAspNetAngularobjAspNetAngular.csproj.nuget.g.props. Generating MSBuild file C:UsersDIDINProjectsAspNetAngularobjAspNetAngular.csproj.nuget.g.targets. Restore completed in 5.82 sec for C:UsersDIDINProjectsAspNetAngularAspNetAngular.csproj. Restore succeeded.
즉, Visual Studio Code의 폴더와 Microsoft Visual Studio의 CSharp Project/Solution에서 직접 열 수 있습니다. 또는 이것을 새로운 것으로 부를 수 있습니다. ASP.NET 이 명령을 입력하여 Core Web API 프로젝트를 실행합니다.
cd AspNetAngular code .
프로젝트는 Visual Studio Code에 의해 열립니다. 아래와 같은 알림이 오면 Yes 버튼을 눌러주세요.
그런 다음 메뉴에서 터미널을 열거나 Ctrl+Shift+`를 누릅니다. 다음 명령을 실행하여 필요한 모든 패키지를 설치하십시오.
dotnet add package Microsoft.EntityFrameworkCore.Tools -v 2.1.2 dotnet add package Microsoft.EntityFrameworkCore.SqlServer -v 2.1.2 dotnet add package Microsoft.EntityFrameworkCore.SqlServer.Design -v 1.1.6 dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design -v 2.1.5 dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Tools -v 2.0.4 dotnet add package AutoMapper.Extensions.Microsoft.DependencyInjection -v 5.0.1
아래와 같은 알림이 표시되면 복원 버튼을 클릭하면 됩니다.
이제 AspNetAngular.csproj 파일에 표시된 올바른 버전이 설치된 이 패키지를 갖게 됩니다.
runtime; build; native; contentfiles; analyzers all
다음으로 패키지 종속성에 오류가 없는지 확인하기 위해 DotNet 애플리케이션을 빌드합니다.
dotnet build
모든 것이 올바른 경로에 있을 때 이 출력을 확인해야 합니다.
Build succeeded. 0 Warning(s) 0 Error(s)
다음으로 Microsoft SQL Server 데이터베이스에 대한 연결을 구성해야 합니다. 먼저 appsettings.json을 열고 편집한 다음 JSON 개체를 로깅하기 전에 이 줄을 추가합니다.
'ConnectionStrings': { 'SQLConnection': 'Server=.;Database=NORTHWND;Trusted_Connection=True;User Id=sa;Password=q;Integrated Security=false;MultipleActiveResultSets=true' },
Startup.cs를 열고 편집한 다음 ConfigureServices 대괄호 안에 이 줄을 추가합니다.
services.AddDbContext(options => options.UseSqlServer(Configuration.GetConnectionString('SQLConnection')));
다음으로 위의 줄 뒤에 CORS를 활성화하려면 이 줄을 추가합니다.
services.AddCors();
또한 Configure 대괄호 안에 이 줄을 추가합니다.
app.UseCors(x => x.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
Configuration에 추가된 라이브러리나 모듈을 가져오는 것을 잊지 마십시오.
3. Microsoft SQL Server 데이터베이스에서 모델 생성
코드 생성 도구 패키지를 사용하여 Northwind 데이터베이스의 모든 테이블을 나타내는 모든 모델을 생성합니다. 이 명령을 실행하여 모델과 해당 컨텍스트를 생성합니다.
dotnet ef dbcontext scaffold 'Server=.;Database=NORTHWND;Trusted_Connection=True;User Id=sa;Password=q;Integrated Security=false;' Microsoft.EntityFrameworkCore.SqlServer -o Models
Models 폴더 안에 생성된 Models와 Context가 보일 것입니다.
IDE 린터에서 많은 경고나 오류가 발생하면 Visual Studio Code를 다시 여세요. 목차에서 볼 수 있듯이 이 자습서에서는 공급자 모델만 사용합니다. 생성된 공급자는 다음과 같습니다.
using System; using System.Collections.Generic; namespace AspNetAngular.Models { public partial class Suppliers { public Suppliers() { Products = new HashSet(); } public int SupplierId { get; set; } public string CompanyName { get; set; } public string ContactName { get; set; } public string ContactTitle { get; set; } public string Address { get; set; } public string City { get; set; } public string Region { get; set; } public string PostalCode { get; set; } public string Country { get; set; } public string Phone { get; set; } public string Fax { get; set; } public string HomePage { get; set; } public ICollection Products { get; set; } } }
해당 모델은 NORTHWNDContext.cs에 Models 폴더 내의 파일로 선언되었습니다.
public virtual DbSet Suppliers { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity(entity => { entity.HasKey(e => e.SupplierId); entity.HasIndex(e => e.CompanyName) .HasName('CompanyName'); entity.HasIndex(e => e.PostalCode) .HasName('PostalCode'); entity.Property(e => e.SupplierId).HasColumnName('SupplierID'); entity.Property(e => e.Address).HasMaxLength(60); entity.Property(e => e.City).HasMaxLength(15); entity.Property(e => e.CompanyName) .IsRequired() .HasMaxLength(40); entity.Property(e => e.ContactName).HasMaxLength(30); entity.Property(e => e.ContactTitle).HasMaxLength(30); entity.Property(e => e.Country).HasMaxLength(15); entity.Property(e => e.Fax).HasMaxLength(24); entity.Property(e => e.HomePage).HasColumnType('ntext'); entity.Property(e => e.Phone).HasMaxLength(24); entity.Property(e => e.PostalCode).HasMaxLength(10); entity.Property(e => e.Region).HasMaxLength(15); }); }
4. 요청 본문 및 응답에 대한 DTO(Data Transfer Object) 생성
요청 본문 및 응답 필드를 지정하기 위해 DTO(Data Transfer Object)를 사용합니다. 이를 위해 새 DTO 폴더를 만들고 해당 폴더 안에 AddSupplierDto.cs, EditSupplierDto.cs, SupplierResponse.cs 파일을 만듭니다. 그런 다음 AddSupplierDto.cs를 열고 편집한 다음 모든 코드를 이것으로 교체합니다.
using System; using System.ComponentModel.DataAnnotations; namespace AspNetAngular.Dtos { public class AddSupplierDto { [Required] public string CompanyName { get; set; } public string ContactName { get; set; } public string ContactTitle { get; set; } public string Address { get; set; } public string City { get; set; } public string Region { get; set; } public string PostalCode { get; set; } public string Country { get; set; } public string Phone { get; set; } public string Fax { get; set; } public string HomePage { get; set; } } }
그런 다음 EditSupplierDto.cs를 열고 편집한 다음 모든 코드를 이것으로 교체합니다.
using System; using System.ComponentModel.DataAnnotations; namespace AspNetAngular.Dtos { public class EditSupplierDto { [Required] public int SupplierId { get; set; } [Required] public string CompanyName { get; set; } public string ContactName { get; set; } public string ContactTitle { get; set; } public string Address { get; set; } public string City { get; set; } public string Region { get; set; } public string PostalCode { get; set; } public string Country { get; set; } public string Phone { get; set; } public string Fax { get; set; } public string HomePage { get; set; } } }
그런 다음 SupplierResponseDto.cs를 열고 편집한 다음 모든 코드를 이것으로 바꿉니다.
namespace AspNetAngular.Dtos { public class SupplierResponseDto { public int SupplierId { get; set; } public string CompanyName { get; set; } public string ContactName { get; set; } public string ContactTitle { get; set; } public string Address { get; set; } public string City { get; set; } public string PostalCode { get; set; } } }
5. 모델 클래스와 DTO 매핑을 위한 도우미 클래스 생성
DTO를 Model 클래스에 매핑하기 위한 도우미를 만들려면 프로젝트 폴더의 루트에 Helpers 폴더를 만든 다음 새 폴더 안에 AutoMapperProfile.cs 파일을 만듭니다. 이 새 파일을 열고 편집한 다음 모든 코드를 이 파일로 바꿉니다.
using AspNetAngular.Dtos; using AspNetAngular.Models; using AutoMapper; namespace AspNetAngular.Helpers { public class AutoMapperProfiles: Profile { public AutoMapperProfiles() { CreateMap(); CreateMap(); CreateMap(); } } }
그런 다음 Startup.cs를 다시 열고 편집한 다음 ConfigureServices 안에 이 줄을 추가합니다.
services.AddAutoMapper();
ConfigureServices에서 라이브러리를 자동으로 가져오는 것을 잊지 마십시오.
6. CRUD(Create, Read, Update Delete) 작업을 위한 리포지토리 생성
리포지토리 클래스와 인터페이스를 생성하려면 프로젝트 폴더의 루트에 Repositories 폴더를 생성해야 합니다. 그런 다음 해당 폴더 안에 IDataRepository.cs라는 이름의 인터페이스 파일을 만든 다음 모든 코드를 이 파일로 바꿉니다.
using System.Threading.Tasks; namespace AspNetAngular.Repositories { public interface IDataRepository where T : class { void Add(T entity); void Update(T entity); void Delete(T entity); Task SaveAsync(T entity); } }
그런 다음 해당 폴더 안에 DataRepository.cs라는 이름의 파일을 만든 다음 모든 코드를 이 파일로 바꿉니다.
using System.Threading.Tasks; using AspNetAngular.Models; namespace AspNetAngular.Repositories { public class DataRepository : IDataRepository where T : class { private readonly NORTHWNDContext _context; public DataRepository(NORTHWNDContext context) { _context = context; } public void Add(T entity) { _context.Set().Add(entity); } public void Update(T entity) { _context.Set().Update(entity); } public void Delete(T entity) { _context.Set().Remove(entity); } public async Task SaveAsync(T entity) { await _context.SaveChangesAsync(); return entity; } } }
그런 다음 Startup.cs를 다시 열고 편집한 다음 ConfigureServices 브래킷 안에 이 줄을 추가합니다.
services.AddScoped(typeof(IDataRepository ), typeof(DataRepository ));
또한 필요한 클래스와 라이브러리를 가져옵니다.
7. CRUD 작업을 위한 컨트롤러 생성
이제 컨트롤러를 통해 API를 사용할 수 있는 방법을 보여드리겠습니다. Supplier 모델에 대한 컨트롤러를 생성합니다. 생성하기 전에 도구를 설치해야 합니다. Visual Studio Code의 터미널에서 이 명령을 실행합니다.
dlib를 설치하는 방법
dotnet tool install --global dotnet-aspnet-codegenerator --version 2.2.1
이 명령을 실행하여 생성하십시오.
dotnet aspnet-codegenerator controller -name SupplierController -api -async -m AspNetAngular.Models.Suppliers -dc NORTHWNDContext -namespace AspNetAngular.Controllers -outDir Controllers
이제 다음과 같은 Supplier의 컨트롤러가 있습니다.
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using AspNetAngular.Models; namespace AspNetAngular.Controllers { [Route('api/[controller]')] [ApiController] public class SupplierController : ControllerBase { private readonly NORTHWNDContext _context; public SupplierController(NORTHWNDContext context) { _context = context; } // GET: api/Supplier [HttpGet] public IEnumerable GetSuppliers() { return _context.Suppliers; } // GET: api/Supplier/5 [HttpGet('{id}')] public async Task GetSuppliers([FromRoute] int id) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var suppliers = await _context.Suppliers.FindAsync(id); if (suppliers == null) { return NotFound(); } return Ok(suppliers); } // PUT: api/Supplier/5 [HttpPut('{id}')] public async Task PutSuppliers([FromRoute] int id, [FromBody] Suppliers suppliers) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != suppliers.SupplierId) { return BadRequest(); } _context.Entry(suppliers).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!SuppliersExists(id)) { return NotFound(); } else { throw; } } return NoContent(); } // POST: api/Supplier [HttpPost] public async Task PostSuppliers([FromBody] Suppliers suppliers) { if (!ModelState.IsValid) { return BadRequest(ModelState); } _context.Suppliers.Add(suppliers); await _context.SaveChangesAsync(); return CreatedAtAction('GetSuppliers', new { id = suppliers.SupplierId }, suppliers); } // DELETE: api/Supplier/5 [HttpDelete('{id}')] public async Task DeleteSuppliers([FromRoute] int id) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var suppliers = await _context.Suppliers.FindAsync(id); if (suppliers == null) { return NotFound(); } _context.Suppliers.Remove(suppliers); await _context.SaveChangesAsync(); return Ok(suppliers); } private bool SuppliersExists(int id) { return _context.Suppliers.Any(e => e.SupplierId == id); } } }
공급자 모델의 원래 필드를 사용하여 생성된 컨트롤러를 볼 수 있습니다. 다음으로 사용자 지정 개체 저장, 편집 및 응답을 위해 이전에 만든 DTO를 사용합니다. Controllers/SupplierController.cs를 열고 편집한 다음 컨텍스트 변수 뒤에 이 변수를 추가합니다.
private readonly IMapper _mapper; private readonly IDataRepository _repo;
또한 SupplierController 생성자에 주입하십시오.
public SupplierController(NORTHWNDContext context, IMapper mapper, IDataRepository repo) { _context = context; _mapper = mapper; _repo = repo; }
필요한 모든 라이브러리 또는 클래스를 가져오는 것을 잊지 마십시오. 그런 다음 HTTPPost 메서드를 이 코드로 바꿉니다.
// POST: api/Supplier [HttpPost] public async Task PostSuppliers([FromBody] AddSupplierDto addSupplierDto) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var preSupplier = _mapper.Map(addSupplierDto); _repo.Add(preSupplier); var saveSupplier = await _repo.SaveAsync(preSupplier); var supplierResponse = _mapper.Map(saveSupplier); return StatusCode(201, new { supplierResponse }); }
그런 다음 HTTPPut 메서드를 이 코드로 바꿉니다.
// PUT: api/Supplier/5 [HttpPut('{id}')] public async Task PutSuppliers([FromRoute] int id, [FromBody] EditSupplierDto editSupplierDto) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != editSupplierDto.SupplierId) { return BadRequest(); } var preSupplier = _mapper.Map(editSupplierDto); _repo.Update(preSupplier); await _repo.SaveAsync(preSupplier); return NoContent(); }
마지막으로 HTTPDelete 메소드를 이것으로 교체합니다. 왜냐하면 우리는 관련된 테이블을 수동으로 busing SQL Query를 삭제할 것이기 때문입니다.
// DELETE: api/Supplier/5 [HttpDelete('{id}')] public async Task DeleteSuppliers([FromRoute] int id) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var suppliers = await _context.Suppliers.FindAsync(id); if (suppliers == null) { return NotFound(); } _context.Database.ExecuteSqlCommand('DELETE FROM [Order Details] WHERE ProductID IN (SELECT ProductID FROM Products WHERE SupplierID = @supplierId)', new SqlParameter('@supplierId', suppliers.SupplierId)); _context.Database.ExecuteSqlCommand('DELETE FROM Products WHERE SupplierID = @supplierId', new SqlParameter('@supplierId', suppliers.SupplierId)); _context.Suppliers.Remove(suppliers); await _context.SaveChangesAsync(); return Ok(suppliers); }
8. Postman을 이용한 API 테스트
이제 실행해야 합니다. ASP.NET 이 명령을 입력하여 터미널에서 Core Web API.
dotnet watch run
watch 키워드는 코드의 변경 사항을 모니터링한 다음 다시 로드하기 위한 추가 명령입니다. ASP.NET 핵심 웹 API 애플리케이션. 그런 다음 Postman 애플리케이션을 열거나 실행합니다. GET 메소드를 사용하고 GET 메소드 뒤의 오른쪽 열을 localhost:5000/api/Supplier로 채우고, 헤더 키는 Content-Type으로, 헤더 값은 application/json으로 채우십시오.
이제 보내기 버튼을 클릭하면 성공적인 GET Supplier에 대한 이 결과가 표시되어야 합니다.
[ { 'supplierId': 1, 'companyName': 'Exotic Liquids', 'contactName': 'Charlotte Cooper', 'contactTitle': 'Purchasing Manager', 'address': '49 Gilbert St.', 'city': 'London', 'region': null, 'postalCode': 'EC1 4SD', 'country': 'UK', 'phone': '(171) 555-2222', 'fax': null, 'homePage': null, 'products': [] }, { 'supplierId': 2, 'companyName': 'New Orleans Cajun Delights', 'contactName': 'Shelley Burke', 'contactTitle': 'Order Administrator', 'address': 'P.O. Box 78934', 'city': 'New Orleans', 'region': 'LA', 'postalCode': '70117', 'country': 'USA', 'phone': '(100) 555-4822', 'fax': null, 'homePage': '#CAJUN.HTM#', 'products': [] }, ... ]
공급업체 ID별로 단일 공급업체를 가져오려면 URL을 localhost:5000/api/Supplier/2로 변경하기만 하면 됩니다. 찾으면 단일 공급업체의 결과를 볼 수 있습니다. 그런 다음 POST의 경우 공급자가 메서드를 POST로 변경하고 URL을 GET 공급자 목록과 동일하게 유지한 다음 본문을 원시 JSON 개체로 채웁니다.
{ 'CompanyName': 'Djamware Inc.', 'ContactName': 'Didin J.', 'ContactTitle': 'CEO', 'Address': 'Whereever Road 123', 'City': 'Bandung', 'Region': 'JBR', 'PostalCode': '12345', 'Country': 'Indonesia', 'Phone': '(022) 123-4567890', 'Fax': '(022) 123-4567890', 'HomePage': 'https://www.djamware.com' }
상태 201과 함께 이 결과를 볼 수 있습니다.
{ 'supplierResponse': { 'companyName': 'Djamware Inc.', 'contactName': 'Didin J.', 'contactTitle': 'CEO', 'address': 'Whereever Road 123', 'city': 'Bandung', 'region': 'JBR', 'postalCode': '12345', 'country': 'Indonesia', 'phone': '(022) 123-4567890', 'fax': '(022) 123-4567890', 'homePage': 'https://www.djamware.com' } }
공급자 데이터를 업데이트하려면 메서드를 PUT으로 변경하고 URL을 localhost:5000/api/Supplier/30으로 변경한 다음 원시 본문에 공급자 ID 필드를 추가합니다.
{ 'SupplierId': 30, 'CompanyName': 'Djamware.com', 'ContactName': 'Didin J.', 'ContactTitle': 'Engineer', 'Address': 'Whereever Road 123', 'City': 'Garut', 'Region': 'JBR', 'PostalCode': '12345', 'Country': 'Indonesia', 'Phone': '(022) 123-4567890', 'Fax': '(022) 123-4567890', 'HomePage': 'https://www.djamware.com' }
성공적인 요청에 대한 응답은 204(콘텐츠 없음)여야 합니다. 다음으로 공급자를 삭제하려면 방법을 DELETE로 변경하고 URL을 이전 방법으로 유지하고 본문을 없음으로 변경하면 됩니다. 응답 본문에서 200개의 응답과 삭제된 데이터가 표시되어야 합니다.
9. Angular 7 CLI 설치 또는 업데이트 및 애플리케이션 생성
Angular 7 CLI를 설치하기 전에 Node.js를 설치했는지 확인하십시오. https://nodejs.org Node.js 명령 프롬프트를 열 수 있습니다. 그런 다음 Node.js 명령 프롬프트를 열고 이 명령을 입력하여 Angular 7 CLI를 설치합니다.
npm install -g @angular/cli
다음으로 루트에 이 명령을 입력하여 Angular 7 응용 프로그램을 만듭니다. ASP.NET 핵심 애플리케이션/프로젝트 디렉토리.
ng new client
여기서 client는 Angular 7 애플리케이션의 이름입니다. 자신의 이름을 지정할 수 있습니다. ASP.NET 핵심 프로젝트 디렉토리. 질문이 있으면 Y와 SASS로 채웁니다. 다음으로 새로 생성된 Angular 7 애플리케이션으로 이동합니다.
cd client
처음으로 Angular 7 애플리케이션을 실행합니다.
ng serve
이제 localhost:4200으로 이동하면 이 페이지가 표시되어야 합니다.
Angular 7 애플리케이션을 중지하려면 CTRL+C 키를 누르기만 하면 됩니다.
10. Angular 7 페이지/컴포넌트 간 탐색 경로 추가
이전 단계에서 질문에 답할 때 Angular 7 Routes를 추가해야 했습니다. 이제 CRUD(Create, Read, Update, Delete) Supplier 데이터에 필요한 페이지를 추가했습니다. 이 명령을 입력하여 Angular 7 구성 요소 또는 페이지를 추가합니다.
ng g component supplier ng g component supplier-detail ng g component supplier-add ng g component supplier-edit
src/app/app.module.ts를 열면 @NgModule 선언에서 가져오고 선언된 구성 요소를 볼 수 있습니다. 그런 다음 src/app/app-routing.module.ts를 열고 편집한 다음 이 가져오기를 추가합니다.
import { SupplierComponent } from './supplier/supplier.component'; import { SupplierDetailComponent } from './supplier-detail/supplier-detail.component'; import { SupplierAddComponent } from './supplier-add/supplier-add.component'; import { SupplierEditComponent } from './supplier-edit/supplier-edit.component';
이러한 배열을 기존 경로 상수에 추가합니다.
const routes: Routes = [ { path: 'supplier', component: SupplierComponent, data: { title: 'List of Suppliers' } }, { path: 'supplier-details/:id', component: SupplierDetailComponent, data: { title: 'Supplier Details' } }, { path: 'supplier-add', component: SupplierAddComponent, data: { title: 'Add Supplier' } }, { path: 'supplier-edit/:id', component: SupplierEditComponent, data: { title: 'Edit Supplier' } }, { path: '', redirectTo: '/supplier', pathMatch: 'full' } ];
src/app/app.component.html을 열고 편집하면 기존 라우터 콘센트가 표시됩니다. 그런 다음 이 HTML 페이지를 CRUD 페이지에 맞게 수정합니다.
src/app/app.component.scss를 열고 편집한 다음 모든 SCSS 코드를 이것으로 바꿉니다.
.container { padding: 20px; }
11. RESTful API 접근을 위한 서비스 생성
액세스 ASP.NET Angular 7 애플리케이션의 Core Web API를 사용하려면 먼저 Angular 7 서비스를 만들어야 합니다. 이 명령을 입력하여 생성합니다.
ng g service api
서비스에서 사용하기 전에 HttpClient 모듈을 등록해야 합니다. src/app/app.module.ts를 열고 편집한 다음 이 가져오기를 추가하십시오.
import { FormsModule } from '@angular/forms'; import { HttpClientModule } from '@angular/common/http'; Add them to the `@NgModule` imports array. imports: [ BrowserModule, FormsModule, HttpClientModule, AppRoutingModule ],
응답 객체의 유형을 지정하려면 ASP.NET Core Web API에 대한 클래스를 만들어야 합니다. 새 파일 src/app/supplier.ts를 만든 다음 이 코드를 추가합니다.
export class Supplier { supplierId: number; companyName: string; contactName: string; contactTitle: string; address: string; city: string; region: string; postalCode: string; country: string; phone: string; fax: string; homePage: string; }
그런 다음 src/app/api.service.ts를 열고 편집한 다음 이 가져오기를 추가합니다.
import { Observable, of, throwError } from 'rxjs'; import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http'; import { catchError, tap, map } from 'rxjs/operators'; import { Supplier } from './supplier';
@Injectable 앞에 이러한 상수를 추가하십시오.
const httpOptions = { headers: new HttpHeaders({'Content-Type': 'application/json'}) }; const apiUrl = 'http://localhost:5000/api/';
생성자에 HttpClient 모듈을 삽입합니다.
constructor(private http: HttpClient) { }
오류 처리기 기능을 추가합니다.
private handleError (operation = 'operation', result?: T) { return (error: any): Observable => { // TODO: send the error to remote logging infrastructure console.error(error); // log to console instead // Let the app keep running by returning an empty result. return of(result as T); }; }
공급자 데이터의 모든 CRUD(생성, 읽기, 업데이트, 삭제) 기능을 추가합니다.
getSuppliers (): Observable { return this.http.get(apiUrl) .pipe( tap(heroes => console.log('fetched Suppliers')), catchError(this.handleError('getSuppliers', [])) ); } getSupplier(id: number): Observable { const url = `${apiUrl}/${id}`; return this.http.get(url).pipe( tap(_ => console.log(`fetched Supplier id=${id}`)), catchError(this.handleError(`getSupplier id=${id}`)) ); } addSupplier (supplier: any): Observable { return this.http.post(apiUrl, supplier, httpOptions).pipe( tap((supplierRes: Supplier) => console.log(`added Supplier w/ id=${supplierRes.supplierId}`)), catchError(this.handleError('addSupplier')) ); } updateSupplier (id: number, supplier: any): Observable { const url = `${apiUrl}/${id}`; return this.http.put(url, supplier, httpOptions).pipe( tap(_ => console.log(`updated Supplier id=${id}`)), catchError(this.handleError('updateSupplier')) ); } deleteSupplier (id: number): Observable { const url = `${apiUrl}/${id}`; return this.http.delete(url, httpOptions).pipe( tap(_ => console.log(`deleted Supplier id=${id}`)), catchError(this.handleError('deleteSupplier')) ); }
12. Angular 7 Material을 사용한 공급자 목록 표시
Angular 7 템플릿에 대한 공급업체 목록을 표시합니다. 먼저 src/app/supplier/supplier.component.ts를 열고 편집한 다음 이 가져오기를 추가합니다.
옴니 부동산 토큰
import { ApiService } from '../api.service';
다음으로 API 서비스를 생성자에 주입합니다.
constructor(private api: ApiService) { }
다음으로 사용자 인터페이스(UI)에 Angular 7 Material 및 CDK를 사용합니다. Table과 같은 Material 구성요소를 구성요소로 생성하기 위한 CLI가 있지만 Table 구성요소를 처음부터 기존 구성요소에 생성하거나 추가합니다. 이 명령을 입력하여 Angular 7 Material을 설치합니다.
ng add @angular/material
몇 가지 질문이 있으면 아래와 같이 답하십시오.
? Choose a prebuilt theme name, or 'custom' for a custom theme: Purple/Green [ Preview: https://material.angular.i o?theme=purple-green ] ? Set up HammerJS for gesture recognition? Yes ? Set up browser animations for Angular Material? Yes
다음으로 필요한 모든 Angular Material 구성 요소 또는 모듈을 src/app/app.module.ts에 등록해야 합니다. 해당 파일을 열고 편집한 다음 이 가져오기를 추가하십시오.
import { MatInputModule, MatPaginatorModule, MatProgressSpinnerModule, MatSortModule, MatTableModule, MatIconModule, MatButtonModule, MatCardModule, MatFormFieldModule } from '@angular/material';
또한 FormsModule 가져오기를 수정하여 ReactiveFormsModule을 추가합니다.
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@NgModule 가져오기에 위의 모듈을 등록합니다.
imports: [ BrowserModule, FormsModule, HttpClientModule, AppRoutingModule, ReactiveFormsModule, BrowserAnimationsModule, MatInputModule, MatTableModule, MatPaginatorModule, MatSortModule, MatProgressSpinnerModule, MatIconModule, MatButtonModule, MatCardModule, MatFormFieldModule ],
그런 다음 src/app/supplier/supplier.component.ts로 돌아가서 이 가져오기를 추가합니다.
import { Supplier } from '../supplier';
생성자 앞에 Angular Material Table Data Source의 변수를 선언합니다.
displayedColumns: string[] = ['supplierId', 'companyName', 'contactName']; data: Supplier[] = []; isLoadingResults = true;
공급자 목록을 즉시 가져오도록 ngOnInit 함수를 수정합니다.
ngOnInit() { this.api.getSuppliers() .subscribe(res => { this.data = res; console.log(this.data); this.isLoadingResults = false; }, err => { console.log(err); this.isLoadingResults = false; }); }
그런 다음 src/app/supplier/supplier.component.html을 열고 편집한 다음 모든 HTML 태그를 이 Angular 7 Material 태그로 바꿉니다.
add Supplier ID {{row.supplierId}} Company Name {{row.companyName}} Contact Name {{row.contactName}}
마지막으로 UI를 약간 조정하려면 src/app/supplier/supplier.component.css를 열고 편집한 다음 이 CSS 코드를 추가합니다.
/* Structure */ .example-container { position: relative; padding: 5px; } .example-table-container { position: relative; max-height: 400px; overflow: auto; } table { width: 100%; } .example-loading-shade { position: absolute; top: 0; left: 0; bottom: 56px; right: 0; background: rgba(0, 0, 0, 0.15); z-index: 1; display: flex; align-items: center; justify-content: center; } .example-rate-limit-reached { color: #980000; max-width: 360px; text-align: center; } /* Column Widths */ .mat-column-number, .mat-column-state { max-width: 64px; } .mat-column-created { max-width: 124px; } .mat-flat-button { margin: 5px; }
13. Angular 7 재질을 사용하여 공급자 세부 정보 표시 및 삭제
Angular 7 Material 테이블 내부의 행 중 하나를 클릭하거나 탭한 후 공급자 세부 정보를 표시하려면 src/app/supplier-detail/supplier-detail.component.ts를 열고 편집한 다음 이 가져오기를 추가하십시오.
import { ActivatedRoute, Router } from '@angular/router'; import { ApiService } from '../api.service'; import { Supplier } from '../supplier';
위의 모듈을 생성자에 주입합니다.
constructor(private route: ActivatedRoute, private api: ApiService, private router: Router) { }
API에서 가져오는 공급자 데이터를 유지하기 위해 생성자 앞에 변수를 선언합니다.
supplier: Supplier = { supplierId: null, companyName: '', contactName: '', contactTitle: '', address: '', city: '', region: '', postalCode: '', country: '', phone: '', fax: '', homePage: '' }; isLoadingResults = true;
API에서 Supplier 데이터를 가져오는 함수를 추가합니다.
getSupplierDetails(id) { this.api.getSupplier(id) .subscribe(data => { this.supplier = data; console.log(this.supplier); this.isLoadingResults = false; }); }
구성 요소가 시작될 때 해당 함수를 호출합니다.
ngOnInit() { this.getSupplierDetails(this.route.snapshot.params['id']); }
공급자 삭제를 위해 이 기능을 추가합니다.
deleteSupplier(id: number) { this.isLoadingResults = true; this.api.deleteSupplier(id) .subscribe(res => { this.isLoadingResults = false; this.router.navigate(['/supplier']); }, (err) => { console.log(err); this.isLoadingResults = false; } ); }
보기의 경우 src/app/supplier-detail/supplier-detail.component.html을 열고 편집한 다음 모든 HTML 태그를 이것으로 바꿉니다.
list Supplier ID: {{supplier.supplierId}}
Company Name: {{supplier.companyName}} - Contact Name:
- {{supplier.contactName}}
- Contact Title:
- {{supplier.contactTitle}}
- Address:
- {{supplier.address}}
- City:
- {{supplier.city}}
- Region:
- {{supplier.region}}
- Postal Code:
- {{supplier.postalCode}}
- Country:
- {{supplier.country}}
- Phone:
- {{supplier.phone}}
- Fax:
- {{supplier.fax}}
- Home Page:
- {{supplier.homePage}}
edit delete
마지막으로 src/app/supplier-detail/supplier-detail.component.css를 열고 편집한 다음 CSS 코드 줄을 추가합니다.
/* Structure */ .example-container { position: relative; padding: 5px; } .example-loading-shade { position: absolute; top: 0; left: 0; bottom: 56px; right: 0; background: rgba(0, 0, 0, 0.15); z-index: 1; display: flex; align-items: center; justify-content: center; } .mat-flat-button { margin: 5px; }
14. Angular 7 머티리얼을 사용하여 공급업체 추가
새로운 공급자를 추가하려면 Angular 7 반응형을 만들어야 합니다. src/app/supplier-add/supplier-add.component.ts를 열고 편집한 다음 이 가져오기를 추가합니다.
import { Router } from '@angular/router'; import { ApiService } from '../api.service'; import { FormControl, FormGroupDirective, FormBuilder, FormGroup, NgForm, Validators } from '@angular/forms';
위의 모듈을 생성자에 주입합니다.
constructor(private router: Router, private api: ApiService, private formBuilder: FormBuilder) { }
생성자 앞에 양식 그룹에 대한 변수와 양식 내부의 모든 필수 필드를 선언하십시오.
supplierForm: FormGroup; companyName = ''; contactName = ''; contactTitle = ''; address = ''; city = ''; region = ''; postalCode = ''; country = ''; phone = ''; fax = ''; homePage = ''; isLoadingResults = false;
각 필드에 대한 초기 유효성 검사를 추가합니다.
ngOnInit() { this.supplierForm = this.formBuilder.group({ 'companyName' : [null, Validators.required], 'contactName' : [null, null], 'contactTitle' : [null, null], 'address' : [null, null], 'city' : [null, null], 'region' : [null, null], 'postalCode' : [null, null], 'country' : [null, null], 'phone' : [null, null], 'fax' : [null, null], 'homePage' : [null, null] }); }
제출 또는 POST 공급자 양식을 위한 기능을 만듭니다.
onFormSubmit(form: NgForm) { this.isLoadingResults = true; this.api.addSupplier(form) .subscribe((res: { [x: string]: any; }) => { const supplier = res['supplierResponse']; const id = supplier['supplierId']; this.isLoadingResults = false; this.router.navigate(['/supplier-details', id]); }, (err) => { console.log(err); this.isLoadingResults = false; }); }
다음으로 ErrorStateMatcher를 구현하기 위해 이 가져오기를 추가합니다.
import { ErrorStateMatcher } from '@angular/material/core';
이 클래스 브래킷이 끝난 후 새 클래스를 만듭니다.
/** Error when invalid control is dirty, touched, or submitted. */ export class MyErrorStateMatcher implements ErrorStateMatcher null): boolean
해당 MyErrorStateMatcher를 기본 클래스의 변수로 인스턴스화합니다.
matcher = new MyErrorStateMatcher();
그런 다음 src/app/supplier-add/supplier-add.component.html을 열고 편집한 다음 모든 HTML 태그를 이것으로 바꿉니다.
list Please enter Company Name save
마지막으로 src/app/supplier-add/supplier-add.component.css를 열고 편집한 다음 이 CSS 코드를 추가합니다.
/* Structure */ .example-container { position: relative; padding: 5px; } .example-form { min-width: 150px; max-width: 500px; width: 100%; } .example-full-width { width: 100%; } .example-full-width:nth-last-child() { margin-bottom: 10px; } .button-row { margin: 10px 0; } .mat-flat-button { margin: 5px; }
15. Angular 7 재질을 사용하여 공급업체 편집
호출 편집 페이지에 대한 Supplier Detail 구성요소 내부에 편집 버튼을 넣었습니다. 이제 src/app/supplier-edit/supplier-edit.component.ts를 열고 편집한 다음 이 가져오기를 추가합니다.
import { Router, ActivatedRoute } from '@angular/router'; import { ApiService } from '../api.service'; import { FormControl, FormGroupDirective, FormBuilder, FormGroup, NgForm, Validators } from '@angular/forms'; import { ErrorStateMatcher } from '@angular/material/core';
위의 모듈을 생성자에 주입합니다.
constructor(private router: Router, private route: ActivatedRoute, private api: ApiService, private formBuilder: FormBuilder) { }
Form Group 변수와 공급자 양식에 필요한 모든 변수를 생성자 앞에 선언합니다.
supplierForm: FormGroup; companyName = ''; contactName = ''; contactTitle = ''; address = ''; city = ''; region = ''; postalCode = ''; country = ''; phone = ''; fax = ''; homePage = ''; isLoadingResults = false; matcher = new MyErrorStateMatcher();
그런 다음 구성 요소가 시작될 때 모든 필드에 대한 유효성 검사를 추가합니다.
뷰 드래그 앤 드롭
ngOnInit() { this.getSupplier(this.route.snapshot.params['id']); this.supplierForm = this.formBuilder.group({ 'companyName' : [null, Validators.required], 'contactName' : [null, null], 'contactTitle' : [null, null], 'address' : [null, null], 'city' : [null, null], 'region' : [null, null], 'postalCode' : [null, null], 'country' : [null, null], 'phone' : [null, null], 'fax' : [null, null], 'homePage' : [null, null] }); }
각 양식 필드에 채워진 공급자 데이터를 가져오는 함수를 만듭니다.
getSupplier(id: number) { this.api.getSupplier(id).subscribe(data => { this.supplierId = data.supplierId; this.supplierForm.setValue({ companyName: data.companyName, contactName: data.contactName, contactTitle: data.contactTitle, address: data.address, city: data.city, region: data.region, postalCode: data.postalCode, country: data.country, phone: data.phone, fax: data.fax, homePage: data.homePage }); }); }
공급자 변경 사항을 업데이트하는 함수를 만듭니다.
onFormSubmit(form: NgForm) { this.isLoadingResults = true; this.api.updateSupplier(this.supplierId, form) .subscribe(res => { this.isLoadingResults = false; this.router.navigate(['/supplier']); }, (err) => { console.log(err); this.isLoadingResults = false; } ); }
공급자 세부 정보 표시 버튼을 처리하는 기능을 추가합니다.
supplierDetails() { this.router.navigate(['/supplier-details', this.supplierId]); }
현재 클래스 뒤에 ErrorStateMatcher를 구현하는 클래스를 추가합니다.
/** Error when invalid control is dirty, touched, or submitted. */ export class MyErrorStateMatcher implements ErrorStateMatcher isErrorState(control: FormControl
그런 다음 src/app/supplier-edit/supplier-edit.component.html을 열고 편집한 다음 모든 HTML 태그를 이것으로 바꿉니다.
list Please enter Company Name update
마지막으로 src/app/supplier-edit/supplier-edit.component.css를 열고 편집한 다음 이 CSS 코드 줄을 추가합니다.
/* Structure */ .example-container { position: relative; padding: 5px; } .example-form { min-width: 150px; max-width: 500px; width: 100%; } .example-full-width { width: 100%; } .example-full-width:nth-last-child() { margin-bottom: 10px; } .button-row { margin: 10px 0; } .mat-flat-button { margin: 5px; }
16. 실행 및 테스트 ASP.NET 핵심 웹 API 및 Angular 7 CRUD 웹 애플리케이션
실행하기 전에 ASP.NET Angular 7 애플리케이션에서 사용하는 Core Web API는 다음을 확인하십시오. ASP.NET 핵심 웹 API는 HTTP로만 제공됩니다. PropertieslaunchSettings.json을 연 다음 applicationUrl에서 https를 제거하기만 하면 됩니다. 그런 다음 Visual Studio Code 터미널에 이 명령을 입력합니다.
dotnet watch run
Angular 7 애플리케이션을 실행하려면 Node.js 명령 프롬프트에서 이 명령을 입력하십시오.
ng serve
이제 브라우저에서 localhost:4200을 가리키면 이 Angular 7 페이지가 표시됩니다.
전체 Angular 7 애플리케이션을 탐색할 수 있습니다.
즉, 다음을 사용하여 웹 앱 빌드의 자습서입니다. ASP.NET 웹 API Angular 7 및 SQL Server. 완전히 작동하는 소스 코드는 다음에서 찾을 수 있습니다. 깃허브 .
더 알아보기
☞ Angular 7(이전의 Angular 2) - 완전한 가이드
☞ Angular(Angular 2+) 및 NodeJS - MEAN 스택 가이드
☞ ASP.NET Core 및 Angular 2(4+)를 사용하여 실제 앱 빌드
☞ ASP NET Core(ASP.NET 5), MVC 6, C#, Angular2 및 EF 단기집중과정
#angular #asp.net #sql-server
codequs.com
ASP.NET Web API Angular 7 및 SQL Server를 사용하여 웹 앱 빌드
ASP.NET Web API, Angular 7 및 Microsoft SQL Server를 사용하여 웹 응용 프로그램을 빌드하는 방법에 대한 포괄적인 단계별 자습서