函数在角度中没有返回值?
2020-02-13
511
我试图获取 ngOnInit 中的第二个函数返回值,但它给出未定义。如果我打印 SvgImage,它就会打印。我不知道我在哪里犯了错误。
ngOnInit() {
this.userService.displayEvents(this.user_id).subscribe(data => {
this.eventArray = [];
if (data.status == 'success') {
data.result.forEach(obj => {
let item = {
id: obj.id,
user_id: obj.user_id,
name: obj.name,
image: this.getSvgImage(obj.category, obj.color_code),
category: obj.category,
start_date: obj.start_date,
status: obj.status,
};
this.eventArray.push(item);
});
this.displayEvents = this.eventArray;
console.log(this.displayEvents);
}
});
}
getSvgImage(categoryID: any, colorCode: any) {
this.userService.getEventCategory().subscribe((data) => {
let SvgImage: any = "";
if (data.status == "success") {
data.result.forEach(obj => {
if (obj.id == categoryID) {
let color = colorCode.replace("#", "");
let SvgImageReplace = obj.image.split('#').pop().split(';')[0];
SvgImage = obj.image.replace(SvgImageReplace, color);
SvgImage = this.sanitized.bypassSecurityTrustHtml(SvgImage);
}
});
}
return SvgImage;
});
}
2个回答
尝试以下修改:
ngOnInit() {
this.userService.displayEvents(this.user_id).subscribe(data => {
this.eventArray = [];
if (data.status == 'success') {
data.result.forEach(obj => {
let item = {
id: obj.id,
user_id: obj.user_id,
name: obj.name,
image: '',
category: obj.category,
start_date: obj.start_date,
status: obj.status,
};
this.eventArray.push(item);
this.getSvgImage(item, obj.category, obj.color_code),
});
this.displayEvents = this.eventArray;
console.log(this.displayEvents);
}
});
}
getSvgImage(item, categoryID: any, colorCode: any) {
this.userService.getEventCategory().subscribe((data) => {
let SvgImage: any = "";
if (data.status == "success") {
data.result.forEach(obj => {
if (obj.id == categoryID) {
let color = colorCode.replace("#", "");
let SvgImageReplace = obj.image.split('#').pop().split(';')[0];
SvgImage = obj.image.replace(SvgImageReplace, color);
SvgImage = this.sanitized.bypassSecurityTrustHtml(SvgImage);
}
});
}
item.image = SvgImage;
});
}
getSvgImage 将获取其第一个参数项目对象,一旦订阅完成,它将更新图像属性。
robert
2020-02-13
函数
getSvgImage
不返回任何内容。调用
this.userService.getEventCategory().subscribe((data) => { ... })
会创建一个
Subscription
,但您甚至不会返回它。
Jacopo Lanzoni
2020-02-13