没有服务提供者-Angular 7

时间:2019-06-05 18:50:43

标签: angular angular6 angular7 angular-services

我已经在Angular中创建了一个 Singleton 服务,该服务会在应用程序启动之前进行API调用。它可以在第一个加载的页面上运行,但是如果我导航到另一个页面,它会显示:

  

错误错误:未捕获(承诺):错误:StaticInjectorError(AppModule)[MyComponent-> MyService]:     StaticInjectorError(平台:核心)[MyComponent-> MyService]:       NullInjectorError:MyService没有提供程序!

我现在不知道为什么,因为该服务被注入到两个组件中,并且可用于第一个组件。

我的app.module.ts

providers: [
        MyService, {
            provide: APP_INITIALIZER,
            useFactory: (myService: MyService) => function () { return myService.load() },
            deps: [MyService],
            multi: true
        }]

我的my.service.ts

@Injectable()
export class MyService {
...
}

两个组件中的导入:

constructor(private myService: MyService) { }

有人可以指导我解决此问题吗?

2 个答案:

答案 0 :(得分:2)

我尝试复制您的问题,但是它对我有用。 请检查此代码。 https://stackblitz.com/edit/angular-palz6c

import { NgModule, APP_INITIALIZER  } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import { MyServiceService } from './my-service.service';
import { TestComponent } from './test/test.component';

@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent, HelloComponent, TestComponent ],
  bootstrap:    [ AppComponent ],
  providers: [MyServiceService, {
            provide: APP_INITIALIZER,
            useFactory: (myService: MyServiceService) => function () { return myService.load() },
            deps: [MyServiceService],
            multi: true
        }]
})
export class AppModule { }

服务

import { Injectable } from '@angular/core';
@Injectable()
export class MyServiceService {

  constructor() { }

  load() {

        // return new Promise<void>((resolve, reject) => {
        //     console.log("AppInitService.init() called");
        //     ////do your initialisation stuff here  
        //     setTimeout(() => {
        //         console.log('AppInitService Finished');
        //         resolve();
        //     }, 6000);

        // });
        console.log('AppInitService Finished');
    }

    test(val){
      console.log('test' + '-' + val);
    }
}

组件:

import { Component, OnInit } from '@angular/core';
import { MyServiceService } from '../my-service.service'
@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {

  constructor(private service: MyServiceService) { 
    console.log(this.service.test('Test Component'));
  }

  ngOnInit() {
  }

}

请让我知道我是否在这里丢失任何东西。

答案 1 :(得分:0)

尝试添加到my.service.ts:

@Injectable({providedin 'root'})
相关问题