簡體   English   中英

將多個服務注入 Angular 庫

[英]Injecting multiple services into an angular library

我制作了一個角度庫,我正在嘗試將幾個服務和常量文件導入到庫中。 但是,當我構建時,我收到錯誤消息,即服務和常量文件應位於庫的“rootDir”下。 有沒有關於我們如何將主應用程序 src 文件夾下的這些文件導入庫並成功構建它的解決方案/方法?

如果你想從應用程序注入一些東西到你的庫,這樣做:

export class LibraryModule {
  static forRoot(config: any): ModuleWithProviders {
    return {
      ngModule: LibraryModule,
      providers: [{provide: 'config', useValue: config}]
    };
  }
}

然后像這樣使用注入的類:

@Component({
  selector: 'app-test',
  templateUrl: './app-test.component.html',
  styleUrls: ['./app-test.component.css']
})
export class AppTestComponent implements OnInit {
  constructor( @Inject('config') config) {
   // use the injected 
 }
}

如何在應用程序模塊中啟用注入:

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
@NgModule({
  imports:      [ BrowserModule, LibraryModule.forRoot(supposeToInject)  ],
  providers:    [ Logger ],
  declarations: [ AppComponent ],
  exports:      [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

你必須確保你的服務用下面的裝飾

@Injectable({providedIn: 'root'})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM