Angular2否在子组件中提供服务的提供者

时间:2016-10-26 20:26:13

标签: angular2-services

我创建了一个简单的骨骼应用程序来显示我在尝试将服务注入子组件时遇到的错误。我正在将服务注入app.module.ts的providers部分,所以我认为这将使应用程序中的服务全局化。如果我从test.compononent.ts中的构造函数参数中删除服务,一切正常。我非常感谢你对这个有任何帮助!

以下是我收到的错误消息。

core.umd.js:3072 ORIGINAL EXCEPTION: No provider for UserService!

以下是 app.module.ts

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent }   from './app.component';
import { UserService } from './services/user.service';
import { NameService } from './services/name.service';
import { TestComponent } from './component/test.component';

@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ AppComponent,TestComponent ],
  bootstrap:    [ AppComponent ],
   providers: [
    UserService,
    NameService
  ]
})
export class AppModule { }

app.component.ts:

import { Component } from '@angular/core';
import { UserService } from './services/user.service';
import { NameService } from './services/name.service';
import { TestComponent } from './component/test.component';

@Component({
  selector: 'my-app',
  template: `
    <h1>My First Angular App</h1>
    <test-component></test-component>
  `,

})
export class AppComponent { 

  constructor(private nameService: NameService, private userService:UserService) {}
}

test.component.ts

import { Component } from '@angular/core';
import { UserService } from '../services/user.service';

@Component({
  selector: 'test-component',
  template: '<h3>test component</h3>'
})
export class TestComponent { 

  constructor(private userService:UserService) {}
}

name.service.ts

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

@Injectable()
export class NameService {
    getName():string {
        return 'name1';
    }
}

user.service.ts

import { Injectable } from '@angular/core';
import { NameService } from './name.service';

@Injectable()
export class UserService {

    constructor(private nameService: NameService) {}
    getUser():string {
        return 'user1';
    }
}

0 个答案:

没有答案