当foreach出现代码问题时,我已经看到了很多方法,但是没有任何作用
我尝试使用for-of,但是没有用
这是我的组件
import { Component, OnInit } from '@angular/core';
import { User } from './../../_models/user';
import { UserService } from './../../_services/user.service';
import { AlertifyService } from './../../_services/alertify.service';
import { ActivatedRoute } from '@angular/router';
import { NgxGalleryOptions, NgxGalleryImage, NgxGalleryAnimation } from 'ngx-gallery';
@Component({
selector: 'app-member-detail',
templateUrl: './member-detail.component.html',
styleUrls: ['./member-detail.component.css']
})
export class MemberDetailComponent implements OnInit {
user: User;
galleryOptions: NgxGalleryOptions[];
galleryImages: NgxGalleryImage[];
constructor(private userService: UserService, private alertify: AlertifyService, private route: ActivatedRoute) { }
ngOnInit() {
this.route.data.subscribe(data => {
this.user = data['user'];
});
this.galleryOptions = [
{
width: '500px',
height: '500px',
imagePercent: 100,
thumbnailsColumns: 4,
imageAnimation: NgxGalleryAnimation.Slide,
preview: false
}
];
this.galleryImages = this.getImages();
}
getImages() {
const imageUrls = [];
for (let i = 0; i < this.user.photos.length; i++) { // The problem is here
imageUrls.push({
small: this.user.photos[i].url,
medium: this.user.photos[i].url,
big: this.user.photos[i].url,
description: this.user.photos[i].description
});
}
return imageUrls;
}
}
我的组件结束
我想在一个用户中显示多张图像。
答案 0 :(得分:1)
问题来自您对ngOnInit
的实现。您正在认购之外呼叫getImages
,那么在您呼叫getImages
的那一刻,this.user
没有价值。
它应该可以解决您的问题:
ngOnInit() {
this.route.data.subscribe(data => {
this.user = data['user'];
this.galleryOptions = [
{
width: '500px',
height: '500px',
imagePercent: 100,
thumbnailsColumns: 4,
imageAnimation: NgxGalleryAnimation.Slide,
preview: false
}
];
this.galleryImages = this.getImages();
});
}
答案 1 :(得分:0)
此行中的错误
for (let i = 0; i < this.user.photos.length; i++)
到
for (let i = 0; i < this.user.length; i++)
答案 2 :(得分:0)
您的循环看起来不错,但是您可以简化它。您从用户那里拍摄照片(可以通过路线进行更改),每次用户更改时都应生成图像。而且,为什么不将此逻辑放在构造函数中?在此示例中,使用ngOnInit
没有任何意义,此外,当调用ngOnInit
时,已经生成了DOM,这是您遇到问题的根源。需要访问组件DOM时应使用ngOnInit
,请参见angular lifecycle hooks的说明。
export class MemberDetailComponent implements OnInit {
user: User;
galleryImages: NgxGalleryImage[];
galleryOptions: NgxGalleryOptions[] = [{
width: '500px',
height: '500px',
imagePercent: 100,
thumbnailsColumns: 4,
imageAnimation: NgxGalleryAnimation.Slide,
preview: false
}];
constructor(private userService: UserService, private alertify: AlertifyService, private route: ActivatedRoute) {
this.route.data.subscribe(data => {
this.user = data['user'];
this.galleryImages = this.user.photos.map(photo => ({
small: photo.url,
medium: photo.url,
big: photo.url,
description: photo.description
});
});
}
}