[英]Angular 8 - @ViewChild returns undefined on parent component. (no nested ngIf and called in ngAfterViewInit)
[英]Angular Nested Component not rendering with ngIf
我只是试图将一个组件嵌套在一个组件内,然后将数组作为嵌套组件的ngFor传递。 问题是数组来自可观察的对象,嵌套组件没有任何渲染。 我可以在浏览器控制台中看到可观察到的返回结果,因此我知道一切都在进行,直到嵌套组件渲染为止。 我知道它与可观察到的返回数据之前发生的渲染有关,但是我无法找到文档或在线信息(或SO问题),这些信息使我指出了我所缺少的内容。
这是代码。
srv-data.service.ts:
interface IWeek { id: number; weeknumofyear: number; year: number; holidaymontype: number; holidaytuetype: number; holidaywedtype: number; holidaythutype: number; holidayfritype: number; } @Injectable() export class SrvDataService { errorMessage: any; private _apiUrl = 'http://172.16.194.250:99/api/'; weeks$: Observable<IWeek[]>; weeks: IWeek[] = []; constructor(private _http: HttpClient) { this.getWeeks() .subscribe(weeks$ => this.weeks = weeks$, error => this.errorMessage = <any>error); } getWeeks(): Observable<IWeek[]> { return this._http.get<IWeek[]>(this._apiUrl + 'Weeks') .do(data => console.log('Weeks from getWeeks(): ' + JSON.stringify(data))) .catch(this.handleError); } }
app.component.ts:
import { Component, OnInit } from '@angular/core'; import { SrvDataService } from './services/srv-data.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', }) export class AppComponent { weeks: IWeek[] = []; constructor (public dataService: SrvDataService) { this.weeks = this.dataService.weeks; } }
app.component.html:
<div> In app.component {{ weeks }} <app-week *ngFor="let week of weeks; index as i; first as isFirst" [week]="week"></app-week> </div>
任何意见是极大的赞赏!
从服务中删除订阅,然后在app.component.html中使用异步管道:
<div>
In app.component {{ weeks }}
<app-week *ngFor="let week of weeks | async; index as i; first as isFirst"
[week]="week">
</app-week>
</div>
不要订阅服务中的Observable,尝试在ngOnInit组件中进行订阅,并在“ this.weeks”中分配响应。 希望对您有所帮助。
调试像“ {{weeks | json}}”这样的星期。 在那里,您应该看到整个对象,否则将看到“ [object Object]”。
如果不起作用,请通过stackblitz分享,我可以为您修复
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.