创建服务类(CourseService):
带参数化构造函数的服务类
import { Injectable } from '@angular/core';
@Injectable()
export class CourseService {
constructor(private name?:string) { }
getName() : string{
return "Service Name is"+ this.name;
}
}
将服务注入Component。
在提供商中,它已经像这样注入了
providers: [
CourseService
]
创建了组件类
import { Component, OnInit } from '@angular/core';
import { CourseService } from '../../services/course.service';
@Component({
selector: 'app-course',
templateUrl: './course.component.html',
styleUrls: ['./course.component.css']
})
export class CourseComponent implements OnInit {
constructor(private courseService: CourseService) { }
ngOnInit() {
let serviceName = this.courseService.getName();
}
}
浏览器控制台错误:
AppComponent.html:1 ERROR Error: StaticInjectorError[CourseService]:
StaticInjectorError[CourseService]:
NullInjectorError: No provider for CourseService!
at _NullInjector.get (core.js:993)
at resolveToken (core.js:1281)
at tryResolveToken (core.js:1223)
at StaticInjector.get (core.js:1094)
at resolveToken (core.js:1281)
at tryResolveToken (core.js:1223)
at StaticInjector.get (core.js:1094)
at resolveNgModuleDep (core.js:10878)
at NgModuleRef_.get (core.js:12110)
at resolveDep (core.js:12608)
如何在组件中注入此服务?
答案 0 :(得分:2)
设计不可能。对于已定义服务的整个范围,Angular的可注入事项是共享的(只有一个实例)。在构造函数中为同一个实例传递不同的参数是没有意义的。如果您需要许多服务实例,可以自己创建,只需执行以下操作:
export class CourseComponent implements OnInit {
private courseService: CourseService;
constructor() {
this.courseService = new CourseService('someName');
}
ngOnInit() {
let serviceName = this.courseService.getName();
}
}