所以,如果我理解错误,我们就有问题了:
homeItems = [
{subject: 'Maths', marks: this.home.maths},//here this.home.math is asynchronous
{subject: 'Science', marks: this.home.science'},
{subject: 'English', marks: this.home.english}
];
在 Angular 中,您可以使用 observables 和 rxjs 管理这个异步数据流。显然这不是让事情正常工作的唯一方法,但是,对我来说更舒服。所以我想你有一个这样的组件
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit{
homeItems = [
{subject: 'Maths', marks: this.home.maths},
{subject: 'Science', marks: this.home.science},
{subject: 'English', marks: this.home.english}
];
home: any;
constructor(
) {
}
ngOnInit() {
this.appService.getHomeResource().subscribe((data: Home) => this.home = data);
}
showHomeResource() {
this.appService.getHomeResource().subscribe((data: Home) => this.home =
data);
}
}
您的问题是,当您初始化 homeItems 时,您正在尝试访问 home,但此时 home 尚未定义。使用 rxjs 执行此操作的方法是:
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit{
homeItems$ = new Observable(); //we can transform homeItems$ in an observable, the $ is a convention
home: any;
constructor(
) {
}
ngOnInit() {
this.homeItems$ = this.appService.getHomeResource().pipe(
map((data: Home) => { //tha map method is like the array.map of js, but are you mapping your data!
this.home = data
return [
{subject: 'Maths', marks: this.home.maths }, //here we can assign to the homeItems$ marks our value. the trick is that in this moment we are not rendering the view, check the html file to understand
{subject: 'Science', marks: this.home.science},
{subject: 'English', marks: this.home.english}
];
})
}
}
如果您看到我们没有在控制器中订阅。因为我们可以在html文件中做的很清楚。
<ng-container *ngIf="homeItems$ | async; let homeItems"> <!-- here we subscribing the observable and we assign the value in homeItems -->
<div class="home_social">
<p *ngFor="let item of homeItems"> Subject: {{item.subject}}" Marks:{{item.marks}}"</p> <!-- here we are sure that we have data -->
</div>
</ng-container>