在组件之前渲染数据

时间:2020-04-21 11:24:41

标签: html angular typescript httpclient

我想使用从html模板中的HttpClient服务加载的数据,但是看起来数据在组件之后呈现,因此我使用指令ngIf解决了问题,但它不起作用!有什么帮助吗?

component.ts:

import { Component, OnInit } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
import { MyserviceService } from '../myservice.service';

@Component({
selector: 'app-forms',
templateUrl: './forms.component.html',
styleUrls: ['./forms.component.css']
})
export class FormsComponent implements OnInit {
ngOnInit() {
this.getBook()

}

constructor(private service : MyserviceService) {
}

Booknames :any

getBook () {
return  this.service.getBookNames().subscribe((data)=> {this.Booknames = data , 
  console.log(this.Booknames)}) ;
}}

component.html:

<div class="example-container">
  <mat-form-field appearance="fill">
      <mat-label>Enter your name</mat-label>
         <input matInput>
  </mat-form-field>
  <mat-form-field appearance="fill">
    <mat-label>Name-linechart</mat-label>
       <input matInput>
 </mat-form-field>

  <mat-form-field *ngIf="BookNames">
    <mat-label>xAxis-linechart</mat-label>
    <mat-select >
      <mat-option  *ngFor="let book of BookNames" >
        {{book}}
      </mat-option>
    </mat-select>
  </mat-form-field> 

当我运行它时,字段“ xAxis-linechart”没有出现!

1 个答案:

答案 0 :(得分:0)

我将* ngIf =“ Booknames”替换为* ngIf =“ BookNames”,我对* ngFor做同样的事情,并且有效! :)