Я очень новичок в угловой. Я пытаюсь вызвать метод Get Web API на кнопке. Теперь я хочу отобразить ответ в HTML. Когда я пытаюсь получить доступ к объекту модели, он говорит, что объект, возможно, «нулевой». Пожалуйста, помогите. < /P> Вот мое приложение. Пожалуйста, смотрите функцию GetPatientByDate. Функция вызывается, и у объекта Res есть данные < /p>
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { Component, inject } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { Observable } from 'rxjs';
import { PatientModel } from '../models/PatientModel.model';
import { AsyncPipe } from '@angular/common';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet,HttpClientModule,AsyncPipe,FormsModule],
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent {
title = 'Patient Details';
http=inject(HttpClient);
patients$=this.GetPatients();
//patient$=this.GetPatientByDate();
inputValue: string = '';
patientDetail:PatientModel|null=null;
private GetPatients():Observable
{
return this.http.get('https://localhost:7076/api/Appointments');
}
showAlert(): void
{
if (this.inputValue) {
this.http.get('https://localhost:7076/api/Appointments ... inputValue).subscribe((res:PatientModel)=>{
alert("Name:"+res.name +" && id:"+res.id+" && Appointment Date:"+res.appointmentDate);
})
} else {
alert("None");
}
}
GetPatientByDate():void
{
this.http.get('https://localhost:7076/api/Appointments ... inputValue).subscribe((res:PatientModel)=>{
this.patientDetail=res;
})
}
}
< /code>
Модель, которую я имею следующим образом < /p>
export interface PatientModel{
id:string
name:string
appointmentDate:string
reason:string
}
< /code>
app.component.html выглядит следующим образом, см. Пациент adetail.name < /p>
{{title}}
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 15px;
}
ID Name Appointment Date Reason
@if(patients$ | async;as patients){
@if(patients.length>0){
@for(item of patients; track $index){
{{item.id}}
{{item.name}}
{{item.appointmentDate}}
{{item.reason}}
}
}
@else{
Nothing found
}
}
Enter Date:
Show Alert
Value bound to component property: {{ inputValue }}
Details:{{patientDetail.name}}
Подробнее здесь: https://stackoverflow.com/questions/796 ... sibly-null