angular - 在加载 http 数据之前 Angular 不渲染 HTML
问题描述
我在加载组件时遇到一些 html 未加载的问题,直到通过服务从 api 调用接收到数据。
以下是相关代码:
import { ApiService } from './services/api.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit, OnDestroy {
thedata;
subscription: Subscription;
constructor(private apiService: ApiService) {}
ngOnInit() {
this.getData();
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
getData() {
this.apiService.getUsers().subscribe(
(res) => {
this.thedata = [res];
},
(err) => {
console.log('There was an error: ' + err);
}
)
}
}
然后在html文件中:
<div *ngFor="let data of thedata">
<!-- other elements here and below -->
{{ data.name }}
</div>
我的问题是,虽然有要渲染的视觉元素,但在加载数据之前它不会渲染。
有没有办法在仍然从 api 加载数据时呈现 html ?
解决方案
它不起作用的原因是初始化组件时没有任何数据。
你可以把它简化成这个。异步管道将负责订阅/取消订阅部分。最重要的是,它将等待数据加载,然后将数据传递给 for 循环。
零件:
import { ApiService } from './services/api.service';
export interface ExpectedDataModel {
name: string;
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
myData: Observable<ExpectedDataModel[]>;
constructor(private apiService: ApiService) {
this.myData = this.apiService.getUsers(); // I suppose this returns an array of objects ///
}
}
模板:
<div *ngFor="let data of myData | async">
<!-- other elements here and below -->
{{ data.name }}
</div>
推荐阅读
- javascript - 当表单编辑角度时,ngb modal 将数据传递给
- python - 使用 python 和 google sheet API 在 google sheet 中插入方程
- pyspark - Azure Synapse:从外部表读取的 PySpark 不起作用
- discord - 如何为不和谐机器人更新创建嵌入式队列列表
- swift - 如何在 Swift 中重置圆形进度条?
- javascript - Firebase 错误帮助(firebase.database 未定义)
- dotnetnuke - 有没有办法使用 C# Razor 模板通过 2sxc 应用程序将 DNN 页面输出到页面?
- x11 - 输入法编辑器如何拦截键盘输入?
- python - 如何通过拖动角来调整多边形的大小?
- c++ - c ++如何在不出错的情况下计算地图