【问题标题】:Rendering data before the component在组件之前渲染数据
【发布时间】:2020-04-21 11:24:41
【问题描述】:

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

组件.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”字段不会出现!

【问题讨论】:

  • 尝试删除 getBook() 中的 return 关键字,并分享您从服务中获取的 JSON(存储在 this.Booknames 中)
  • @ShlokNangia 不,它仍然无法正常工作
  • 尝试*ngIf="Booknames" 而不是*ngIf="BookNames",*ngFor 迭代也是如此

标签: html angular typescript httpclient


【解决方案1】:

我将 *ngIf="Booknames" 替换为 *ngIf="BookNames",我对 *ngFor 做同样的事情,它可以工作! :)

【讨论】:

    猜你喜欢
    • 2017-07-23
    • 1970-01-01
    • 2018-02-19
    • 1970-01-01
    • 2019-02-08
    • 2016-06-09
    • 2021-04-19
    • 2018-11-29
    相关资源
    最近更新 更多