我正在尝试使用ReflectiveInjector
向通用类注入2个服务,如SO
我第一次在ReflectiveInjector
上调用DebugService
它完全正常,但如果我用CourseService
替换它,我会收到以下InvalidProviderError:
Uncaught InvalidProviderError_nativeError:错误:无效的提供程序 - 仅允许Provider和Type的实例,得到:undefined
<小时/> 这是我尝试注入服务的通用类。
Media.ts
////////////////////////////////////////////////////////////////////////////////////////
import { ReflectiveInjector } from '@angular/core';
// other imports
////////////////////////////////////////////////////////////////////////////////////////
import { CourseService , DebugService } from 'app/services';
//other imports
////////////////////////////////////////////////////////////////////////////////////////
export class Media {
private sanitizer: DomSanitizer;
private courseService: CourseService;
private debug: DebugService;
constructor(_audio: File[], _images: File[], _videos: File[] ) {
// works fine
var injector = ReflectiveInjector.resolveAndCreate([DebugService]);
this.debug = injector.get(DebugService);
// throws InvalidProviderError
var injector2 = ReflectiveInjector.resolveAndCreate([CourseService]);
this.courseService = injector2.get(CourseService);
}
<小时/> 这两项服务如下:
debug.service.ts
////////////////////////////////////////////////////////////////////////////////////////
import { Injectable } from '@angular/core';
////////////////////////////////////////////////////////////////////////////////////////
import { environment } from '../../environments/environment';
////////////////////////////////////////////////////////////////////////////////////////
@Injectable()
export class DebugService {
constructor() {
/*stuff*/
}
}
航向service.service.ts
////////////////////////////////////////////////////////////////////////////////////////
import { Injectable, EventEmitter, Output } from '@angular/core';
import { Router } from '@angular/router';
import { Title, DomSanitizer, SafeResourceUrl, SafeUrl} from '@angular/platform-browser';
////////////////////////////////////////////////////////////////////////////////////////
import { DebugService } from 'app/services';
////////////////////////////////////////////////////////////////////////////////////////
@Injectable()
export class CourseService {
@Output() preloadData = new EventEmitter<any>();
// Constructor 1 - called on instantiation of class
constructor(
private sanitizer: DomSanitizer,
private router: Router,
private titleService: Title,
private debug: DebugService
) { /*stuff*/ }
<小时/> 当我手动将
Media
和CourseService
作为参数传递给Media构造函数时,这些服务已在DebugService
类中成功使用,但是想要远离它,因为它似乎非常&#39;笨重&#39;与此更简化的方法相比。
即
export class Media {
/*stuff*/
constructor(_audio: File[], _images: File[], _videos: File[], _courseService: CourseService, _debugService: DebugService ) { /*stuff*/ }
}
媒体目前在另一个班级的构造函数中定义:
var preloader = new Preloader(
new Media(
// Audio Files
[
new File(0, './app/assets/video/Example1.mp3')
],
// Image Files
[
],
// Video Files
[
new File(0, './app/assets/video/Example1.mp4')
]
)
//...