Не могу вывести объект на экран из БД в Angular
Решил посмотреть, что такое Angular 12 и как он работает с .NET Задача вроде бы простая, но ничего не получается: нужно всего лишь вывести на экран объекты из БД, но я получаю пустоту. Вот на этой странице хочу вывести:
<div class="bg-secondary p-5 rounded-lg m-3 text-light">
<div class="display-4 text-center">Payment Detail Register</div>
</div>
<div class="row">
<div class="col-md-6">
<app-payment-detail-form></app-payment-detail-form>
</div>
<div class="col-md-6 pt-4">
<table class="table">
<thead class="thead-light">
<tr>
<th>Card Owner</th>
<th>Card Number</th>
<th>Exp. Date</th>
<th></th>
</tr>
</thead>
<tbody>
<tr *ngFor="let pd of service.list">
<td (click)="populateForm(pd)">{{pd.cardOwnerName}}
</td>
<td (click)="populateForm(pd)">{{pd.cardNumber}}</td>
<td (click)="populateForm(pd)">{{pd.expirationDate}}
</td>
<td><i class="far fa-trash-alt fa-lg text-danger"
(click)="onDelete(pd.paymentDetailId)"></i></td>
</tr>
</tbody>
</table>
</div>
</div>
Вот здесь я создаю обращение к БД
import { Injectable } from '@angular/core';
import { PaymentDetail } from './payment-detail.model';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class PaymentDetailService {
constructor(private http: HttpClient) { }
formData: PaymentDetail = new PaymentDetail();
readonly baseURL = 'http://localhost:1960/api/PaymentDetail'
list: PaymentDetail[];
postPaymentDetail() {
return this.http.post(this.baseURL, this.formData);
}
putPaymentDetail() {
return
this.http.put(`${this.baseURL}/${this.formData.paymentDetailId}`,
this.formData);
}
deletePaymentDetail(id: number) {
return this.http.delete(`${this.baseURL}/${id}`);
}
refreshList() {
this.http.get(this.baseURL)
.toPromise()
.then(res => this.list = res as PaymentDetail[]);
}
}
В дальнейшем нужно реализовать функции на удаление и изменение объекта, но соответственно оно не работает. Что-то не так с моим массивом list: PaymentDetail[];
Я только учусь всему этому делу, поэтому нашел видео с таким уроком, но там используют Angular 11, а у меня установился Angular 12. Помогите, пожалуйста, решить данную проблему. Ибо на собеседованиях часто спрашиваю, как связать фронтэнд с базой данных, а я не могу этого сделать, у меня выходит пустота. Заранее спасибо!
добавил файл компонент
import { Component, OnInit } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { PaymentDetail } from '../shared/payment-detail.model';
import { PaymentDetailService } from '../shared/payment-
detail.service';
@Component({
selector: 'app-payment-details',
templateUrl: './payment-details.component.html',
styles: [
]
})
export class PaymentDetailsComponent implements OnInit {
constructor(public service: PaymentDetailService,
private toastr: ToastrService) { }
ngOnInit(): void {
this.service.refreshList();
}
populateForm(selectedRecord: PaymentDetail) {
this.service.formData = Object.assign({}, selectedRecord);
}
onDelete(id: number) {
if (confirm('Are you sure to delete this record?')) {
this.service.deletePaymentDetail(id)
.subscribe(
res => {
this.service.refreshList();
this.toastr.error("Deleted successfully", 'Payment Detail
Register');
},
err => { console.log(err) }
)
}
}
}
еще один компонент
import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
import { ToastrService } from 'ngx-toastr';
import { PaymentDetail } from 'src/app/shared/payment-detail.model';
import { PaymentDetailService } from 'src/app/shared/payment-detail.service';
@Component({
selector: 'app-payment-detail-form',
templateUrl: './payment-detail-form.component.html',
styles: [
]
})
export class PaymentDetailFormComponent implements OnInit {
constructor(public service: PaymentDetailService,
private toastr: ToastrService) { }
ngOnInit(): void {
}
onSubmit(form: NgForm) {
if (this.service.formData.paymentDetailId == 0)
this.insertRecord(form);
else
this.updateRecord(form);
}
insertRecord(form: NgForm) {
this.service.postPaymentDetail().subscribe(
res => {
this.resetForm(form);
this.service.refreshList();
this.toastr.success('Submitted successfully', 'Payment Detail Register')
},
err => { console.log(err); }
);
}
updateRecord(form: NgForm) {
this.service.putPaymentDetail().subscribe(
res => {
this.resetForm(form);
this.service.refreshList();
this.toastr.info('Update successfully', 'Payment Detail Register')
},
err => { console.log(err); }
);
}
resetForm(form: NgForm) {
form.form.reset();
this.service.formData = new PaymentDetail();
}
}