因此,我有一个服务,并且在其中有返回承诺的方法。在我的component.ts
文件中,我注入了服务,然后尝试在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>
我需要操纵ngAfterViewinit
内部的DOM元素,但是它返回一个空的nodeList。其他一切工作正常,我将所有数据取回,<ng-template>Loading</ng-template>
显示然后按预期消失。
我需要知道如何成功定位这些DOM元素。
任何帮助将不胜感激。