2017-02-10 32 views
0

我創建了一個名爲SecurityService的簡單服務。這是代碼:「我的Angular 2.0.0項目中沒有提供商」

import { Injectable } from '@angular/core'; 

@Injectable() 
export class SecurityService { 
    items: any[]; 

    constructor() { 
     this.items = [ 
      { name: 'User 1' }, 
      { name: 'User 2' }, 
      { name: 'User 3' } 
     ]; 
    } 

    getItems() { 
     return this.items; 
    } 
} 

而爲了利用這項服務,我創建了一個簡單的頁面。

import { Component } from '@angular/core'; 
import { SecurityService } from '../services/security.service' 

@Component({ 
    selector: 'test-page', 
    template: require('./test/test.page.html'), 
    providers: [SecurityService] 
}) 
export class TestPage { 
    items: any[]; 

    constructor(private securitySvc: SecurityService) { 
      this.items = securitySvc.getItems(); 
    } 
} 

當我加載此頁面時,收到「沒有爲SecurityService提供提供程序!」的錯誤。經過很多搜索,我無法弄清楚這個問題的解決方案。

我應該發佈任何其他內容來幫助解決此問題。

非常感謝所有幫助。

  • sroye98
+1

提供的代碼是完全有效的,嘗試重新申請,重新啓動納克服務。 – kemsky

+0

難道是SecurityService以某種方式在給定的'test-page'組件之前得到實例化嗎? – longbow

+2

爲了測試目的,嘗試在AppModule中提供SecurityService而不是TestPage – mickdev

回答

0

我不知道到底發生了什麼,但只要我重建的Visual Studio 2015中應用程序的應用開始工作。正如kemsky所說的那樣,代碼很好,可能與Visual Studio有關。

0

除此之外,您還顯示什麼,該服務還可以在模塊級進行註冊:

import { NgModule } from '@angular/core'; 
 
import { BrowserModule } from '@angular/platform-browser'; 
 
import { HttpModule } from '@angular/http'; 
 

 
import { ConfigurationService } from './services/configuration.service'; 
 

 
@NgModule({ 
 
    imports: [ 
 
    BrowserModule, 
 
    HttpModule 
 
    ], 
 
    declarations: [ 
 
    //... 
 
    ], 
 
    providers: [ 
 
    ConfigurationService 
 
    ], 
 
    bootstrap: [ AppComponent ] 
 
}) 
 
export class AppModule { }