【发布时间】: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