angular - 在 Angular 组件 ngAfterViewInit 中定位 DOM 元素返回空 nodeList
问题描述
所以,我有一个服务,里面有返回承诺的方法。在我的component.ts
文件中,我正在注入服务,然后尝试在 a 中调用它的方法,Promise.all([])
因为在渲染视图之前我需要服务的所有结果。
我这样做的方式是通过*ngIf
模板的容器元素上的指令来检查服务的结果是否全部返回(通过一个名为 的变量pageReady
),然后呈现模板。
我的 component.ts 文件...
import { Component, OnInit, ElementRef, Renderer2, AfterViewInit } from '@angular/core';
import { MyService } from './services/myservice.service';
@Component({...})
export class MyComponent implements OnInit, AfterViewInit {
public pageReady: Promise<boolean>;
public items;
public items2;
public nodelist;
constructor( private service: MyService, private el: ElementRef ) { }
ngOnInit() {
this.fetchData();
}
/* This right here is my problem */
ngAfterViewInit() {
this.nodelist = this.el.nativeElement.querySelectorAll('.items figure');
console.log(this.nodelist);
}
private getFirstItem() {
return this.service.serviceMethodOne(); /* Returns promise */
}
private getSecondItem() {
return this.service.serviceMethodTwo(); /* Returns promise */
}
private async fetchData() {
return await Promise.all([this.getFirstItem(), this.getSecondItem()]).then(res => {
// Assign returned values to class variables that will be used in the template
this.items = res[0];
this.items2 = res[1];
this.pageReady = Promise.resolve(true);
});
}
}
模板文件...
<div class="container" *ngIf="pageReady | async ; else loading">
<section class="items">
<figure *ngFor="let item of items">
<img src="{{ item.path }}" alt="{{ item.title }}">
</figure>
</section>
<section class="items2">
<div class="item2" *ngFor="let item2 of items2">
<p>{{ item2.name }}</p>
</div>
</section>
</div>
<ng-template #loading>Loading...</ng-template>
我需要操作内部定位的 DOM 元素,ngAfterViewinit
但它返回一个空的 nodeList。其他一切正常,我取回所有数据,<ng-template>Loading</ng-template>
然后显示按预期消失。我需要知道如何成功定位那些 DOM 元素。
任何帮助将不胜感激。
解决方案
推荐阅读
- spring-boot - 合并来自两个不同服务器的日志
- python-3.x - 检查目标时出错:预期 conv2d 有 4 个维度,但得到了具有形状的数组
- reactjs - 测试一个笑话模拟函数本身
- python - TypeError: 'encoding' is an invalid keyword argument for this function - 我该如何解决?
- react-native - React Native - 异常'- [NSNull length]:在调用multiSet时抛出无法识别的选择器发送到实例0x1e6c059b0'
- php - 没有函数的字符串执行
- firebase - Firebase 网络挂钩
- python - 为什么 pandas.series.describe 和 pandas.series.describe() 给出不同的结果?
- c - Linux sound programming. How to determine a buffer size in frames?
- rest - 奇怪的 IIS/WCF Web 服务问题