首页 文章

以角度6将参数从组件发送到服务构造函数

提问于
浏览
1

我是angular6中的新手,当我从组件发送参数到服务时,我得到StaticInjectorError . 怎么了?

我的代码就像这个组件:

import { Component, Input, OnInit } from '@angular/core';
import { myService } from '../../@core/data/myService';
@Component({
  selector: 'table',
  templateUrl: './table.component.html'
})
export class TableComponent implements OnInit {
  constructor(private service: myService) {
  }
  ngOnInit() {
    this.service = new myService ("name");
}

服务:

import { Injectable, Inject } from '@angular/core';
    import { Observable } from 'rxjs/Observable';
    import { DataService } from './data.service';

    @Injectable() export class myService {

        constructor(
            entityName: string,
        ) {
            console.log(entityName);
        }
    }

app.module.ts:

import { myService } from './@core/data/myService '
import { TableModule } from './pages/table/table.module';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    HttpClientModule,
    AppRoutingModule,

    NgbModule.forRoot(),
    ThemeModule.forRoot(),
    CoreModule.forRoot(),
  ],
  bootstrap: [AppComponent],
  providers: [
    myService,
    TableModule
  ],
})
export class AppModule {
}

错误消息:ProductsComponent.html:1错误错误:StaticInjectorError(AppModule)[BDBaseService - > String]:StaticInjectorError(Platform:core)[BDBaseService - > String]:NullInjectorError:没有String的提供者! atInullInjector.push ../ node_modules/@angular/core/fesm5/core.js.NullInjector.get(core.js:979)at resolveToken(core.js:1232)at tryResolveToken(core.js:1182)at StaticInjector在StaticInjector.push的tryResolveToken(core.js:1182)的resolveToken(core.js:1232)的.push ../ node_modules/@angular/core/fesm5/core.js.StaticInjector.get(core.js:1077)位于_createClass(core.js:9283)的resolveNgModuleDep(core.js:9238)处的_/node_modules/@angular/core/fesm5/core.js.StaticInjector.get(core.js:1077)位于_createProviderInstance $ 1(核心 . JS:9255)

1 回答

  • 0

    你不做 this.service = new myService ("name"); . 服务是在某个地方提供的那一刻创建的 . 在您的情况下,在 app.module.ts . 这意味着整个应用程序将只使用此服务的一个实例 . 如果需要多个实例,则必须在模块或组件中再次提供它 . 如果在不同级别上多次提供服务(例如,在app.module和组件中),则使用在最低级别提供的服务 .

    要在组件中提供服务,只需在@Component装饰器中添加行:

    @Component({
        selector: 'table',
        templateUrl: './table.component.html',
        providers: [myService], // <---
    })
    

    如果您在构造时绝对需要将一些值传递给此服务,请参阅this answer(我希望它仍然是实际的)

相关问题