与服务,component.ts和component.html的通信不起作用

时间:2019-05-20 18:05:38

标签: angular

@Injectable({
  providedIn: 'root'
})
export class PatientService {
listpatient;
  constructor(private httpClient:HttpClient) {
    this.httpClient.get("http://localhost:8010/patients").subscribe(data=>{this.listpatient=data;},err=>{console.log(err);})
   }
}

---------------------------------------    
@Component({
  selector: 'app-pat',
  templateUrl: './patient.component.html',
  styleUrls: ['./patient.component.css'],
})
export class PatientComponent implements OnInit {
@Input()listpatient;  
  constructor(patient:PatientService){
   this.listpatient=patient.listpatient;
  }

  ngOnInit() {}
}
---------------------------------------
<table *ngIf="listpatient" class="table">//he don't enter in the table
  <tr>
  <th>ID</th><th>Nom</th><th>Prenom</th> <th></th> 
</tr>

  <tr  *ngFor="let f of listpatient">
    <td>{{f.id}}</td>
    <td>{{f.nom}}</td>
    <td>{{f.prenom}}</td>

    <td routerLink="patientdetail" routerLinkActive="active" type="button" class="btn btn-light">Obtenir les infos</td>

</tr> 
</table>

我从春季开始加载患者名单,但是我有一个问题,它没有显示我的名单,我认为我无法将数据发送到html。它不会输入*ngIf

3 个答案:

答案 0 :(得分:0)

在您的服务中,您应该有一个方法,它应该将调用返回给数据库

patientlist() {
return this.httpClient.get("http://localhost:8010/patients")
}

此外,我相信您应该订阅组件而不是服务

this.patient.patientlist.subscribe(data=>{this.listpatient=data;},err=>{console.log(err);})

答案 1 :(得分:0)

如下所示在服务类中创建方法getPatients(),然后在组件中调用该方法。

Service.ts

@Injectable({
    providedIn: 'root'
})
export class PatientService {
    listpatient;
    constructor(private httpClient: HttpClient) { }

    getPatients() {
        this.httpClient.get("http://localhost:8010/patients")
            .map(data => { return data; });
    }
}

Component.ts

@Component({
    selector: 'app-pat',
    templateUrl: './patient.component.html',
    styleUrls: ['./patient.component.css'],
})
export class PatientComponent implements OnInit {
    @Input() listpatient;
    constructor(patient: PatientService) {

    }

    ngOnInit() {
        this.patient.getPatients().subscribe(data => {
            this.listpatient = data;
        });
    }
}

答案 2 :(得分:0)

我暂时解决了这个问题

export class PatientComponent implements OnInit {
  @Input() listpatient;
  constructor(private httpClient:HttpClient){
  }

  ngOnInit() {
    this.httpClient.get("http://localhost:8010/patients").subscribe(data=>{this.listpatient=data})
  }
}