我遇到了错误
question-images.service.ts(5,2):模板的编译过程中出错 'QuestionImagesService'只有初始化的变量和常量可以 在装饰器中被引用,因为此变量的值为 模板编译器在“可注入”中需要的 “可注射”引用“可注射” “可注射”引用“可注射” 未将Injectable初始化为.. \ @ angular \ core \ src \ di \ metadata.ts(138,22)
这是组件
import { Component, OnChanges, OnInit } from '@angular/core';
import { SafeHtml } from '@angular/platform-browser';
import { QuestionImagesService } from '@app/patient/components/assesment/questions/question-images.service';
import { QuestionBase } from '@app/patient/components/assesment/questions/question.base';
@Component({
selector: 'ez-slider-question',
templateUrl: './slider-question.component.html',
styleUrls: ['./slider-question.component.scss'],
providers: [QuestionImagesService]
})
export class SliderQuestionComponent extends QuestionBase implements OnInit, OnChanges {
minValue: number;
maxValue: number;
value: number;
smallStep: number;
imageId = 0;
images: { [key: number]: SafeHtml } = {};
constructor(private questionImagesService: QuestionImagesService) { super(); }
ngOnInit() {
this.minValue = 1;
this.smallStep = 1;
this.maxValue = this.question.answers.length;
this.value = this.question.userAnswers[0]
? Number(this.question.answers.find(answer => answer.id === this.question.userAnswers[0].id).value)
: this.minValue;
this.images = this.questionImagesService.startLoadingImages(this.question);
}
getNewUserAnswerValues(): string[] {
return [this.value.toString()];
}
onValueChange(value: number) {
this.imageId = this.question.answers.find(answer => answer.value === value.toString()).id;
}
这是服务
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core/src/core';
import { SafeHtml, DomSanitizer } from '@angular/platform-browser';
@Injectable()
export class QuestionImagesService {
private images: { [key: number]: SafeHtml } = {};
constructor(private httpClient: HttpClient, private domSanitizer: DomSanitizer) { }
startLoadingImages(question: IQuestion): { [key: number]: SafeHtml } {
this.images = {};
question.answers.forEach(answer => {
if (answer.imageUrl) {
this.httpClient.get(`http://localhost:54531/${answer.imageUrl}`, { responseType: 'text' })
.subscribe(imageHtml => this.images[answer.id] = this.domSanitizer.bypassSecurityTrustHtml(imageHtml));
}
});
return this.images;
}
}
在执行ng serve --aot
期间引发了错误。我试图谷歌和使用服务工厂,但没有成功。我想以这种方式提供服务,因为我希望每个组件都有一个实例。你知道如何实现吗?
答案 0 :(得分:2)
问题是您从Injectable
内部错误的路径导入QuestionImagesService
。将导入更改为:
import { Injectable } from '@angular/core';