Angular 2服务依赖项注入失败(使用Angular cli和$ng serve)
我在Angular 2中使用依赖项注入将服务注入组件。代码如下:Angular 2服务依赖项注入失败(使用Angular cli和$ng serve),angular,angular2-services,angular-cli,Angular,Angular2 Services,Angular Cli,我在Angular 2中使用依赖项注入将服务注入组件。代码如下: /app/source display/source display.component.ts: import { Component, OnInit } from '@angular/core'; import { CatalogService } from '../catalog.service'; @Component({ moduleId: module.id, selector: 'app-source-di
/app/source display/source display.component.ts
:
import { Component, OnInit } from '@angular/core';
import { CatalogService } from '../catalog.service';
@Component({
moduleId: module.id,
selector: 'app-source-display',
providers: [CatalogService],
templateUrl: 'source-display.component.html',
styleUrls: ['source-display.component.css']
})
export class SourceDisplayComponent implements OnInit {
active_source_id: number;
sources: any;
constructor(catalogService: CatalogService) {
this.active_source_id = 1;
this.sources = catalogService.getCatalog();
}
ngOnInit() {
// active_source_id = 0;
}
}
import { Injectable } from '@angular/core';
@Injectable()
export class CatalogService {
constructor() {}
getCatalog() {
return {
0: {name: 'Source 0'},
1: {name: 'Source 1'},
}
}
}
/app/catalog.service.ts
:
import { Component, OnInit } from '@angular/core';
import { CatalogService } from '../catalog.service';
@Component({
moduleId: module.id,
selector: 'app-source-display',
providers: [CatalogService],
templateUrl: 'source-display.component.html',
styleUrls: ['source-display.component.css']
})
export class SourceDisplayComponent implements OnInit {
active_source_id: number;
sources: any;
constructor(catalogService: CatalogService) {
this.active_source_id = 1;
this.sources = catalogService.getCatalog();
}
ngOnInit() {
// active_source_id = 0;
}
}
import { Injectable } from '@angular/core';
@Injectable()
export class CatalogService {
constructor() {}
getCatalog() {
return {
0: {name: 'Source 0'},
1: {name: 'Source 1'},
}
}
}
我还将我的
CatalogService
放在main.ts文件的boostrap函数中
以下是我在命令行中运行ng serve
时收到的错误消息(来自):
我注意到一些奇怪的事情:代码没有按原样工作,但是如果我从组件中注释掉这一部分--
--然后运行ng serve
(它成功构建了应用程序),然后取消对该部分的注释,应用程序现在按照我希望的方式刷新
我不知道该怎么解决这个问题。有什么想法吗?我的依赖项注入本身是否存在问题,或者仅使用此命令是否存在其他问题?您的代码中有两个错误:
constructor(private catalogService: CatalogService) {
this.active_source_id = 1;
this.sources = this.catalogService.getCatalog();
}
构造函数(私有catalogService:catalogService)
相当于:
export class SourceDisplayComponent {
private catalogService;
constructor(catalogService: CatalogService) {
this.catalogService=catalogService; //initialising instance variable with dynamically injected instance
}
}
希望这能有所帮助。注释
源代码display.component.spec.ts
让它对我有用!如果我不加评论,我真的失去了应用程序的功能吗?或者.spec.ts文件仅用于测试等。?我还修复了我的构造函数,感谢您的洞察力。@Arjunspec.ts
文件是angular cli配置的测试用例。如果您熟悉这些测试用例,那么编辑它们就很容易了。促进发展。您不会丢失应用程序的功能。