我只是尝试在组件中嵌套组件,并将数组作为嵌套组件的ngFor传递。问题是数组是来自可观察的,并且没有任何东西是嵌套组件的渲染。我可以在浏览器控制台中看到observable返回,所以我知道一切都在嵌套组件渲染的点上。我知道它与在可观察的返回数据之前发生的渲染有关,但我无法找到指向我所缺少的文档或在线信息(或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>
非常感谢任何建议!
答案 0 :(得分:1)
从服务中删除订阅,并在app.component.html中使用async管道:
<div>
In app.component {{ weeks }}
<app-week *ngFor="let week of weeks | async; index as i; first as isFirst"
[week]="week">
</app-week>
</div>
答案 1 :(得分:0)
不要订阅服务中的Observable,尝试在ngOnInit组件中进行订阅,并在“ this.weeks”中分配响应。希望会有所帮助。
调试像“ {{weeks | json}}”这样的星期。在那里,您应该看到整个对象,否则将看到“ [object Object]”。
如果这不起作用,请通过stackblitz分享,我可以为您修复