2016-11-12 87 views
9

参数的服务我已经被启动,需要一定的价值服务:Angular2 - 注入需要初始化

@Injectable() 
export class MyService { 
    private myVals: any; 

    constructor(init : any) { 
    this.myVals = init; 
    } 
} 

和消费者:

@Component(...) 
export class MyComponent { 
    private svc: MyService; 
    constructor(private svc : MyService) { 
    } 
} 

那么,有没有办法注入并在依赖注入期间将所需参数传递给MyService的构造函数?就像:

constructor(private svc({ // init vales }) : MyService) {} 

我知道我可以通过变量和所有,但有兴趣找到是否有一种方法来从API做到这一点。

回答

-1

看我的代码,你可以在服务这样

//our root app component 
import {Component, NgModule, Injectable} from '@angular/core' 
import {BrowserModule} from '@angular/platform-browser' 


@Component({ 
    selector: 'my-app', 
    template: ` 
    <div> 
     <h2>Hello {{name}}</h2> 
    </div> 
    `, 
}) 
export class App { 
    name:string; 
    private myService; 
    constructor() { 
    this.myService = new MyService('value'); 
    this.name = 'Angular2' 
    } 
} 



@Injectable() 
export class MyService { 
    private myInit:any; 

    constructor(init: any) { 
    this.myInit = init; 
    console.log('init', this.myInit); 
    } 
} 




@NgModule({ 
    imports: [ BrowserModule ], 
    declarations: [ App ], 
    bootstrap: [ App ] 
}) 
export class AppModule {} 
+2

你正在实例化而不是注入。如果走这条路线,我更愿意使用'constructor(private myService:MyService){myService.name ='Angular2'; }'实际上已经注入了服务。 – gt6707a

9

注入参数有是角团队建议here正式的方式。它基本上允许你注入静态类型的配置类。

我已经成功地实现了它,这里是所有相关代码:

1)app.config.ts

import { OpaqueToken } from "@angular/core"; 

export let APP_CONFIG = new OpaqueToken("app.config"); 

export interface IAppConfig { 
    apiEndpoint: string; 
} 

export const AppConfig: IAppConfig = {  
    apiEndpoint: "http://localhost:15422/api/"  
}; 

2)app.module.ts

import { APP_CONFIG, AppConfig } from './app.config'; 

@NgModule({ 
    providers: [ 
     { provide: APP_CONFIG, useValue: AppConfig } 
    ] 
}) 

3)your.service.ts

import { APP_CONFIG, IAppConfig } from './app.config'; 

@Injectable() 
export class YourService { 

    constructor(@Inject(APP_CONFIG) private config: IAppConfig) { 
      // You can use config.apiEndpoint now 
    } 
} 

现在,您可以在不使用字符串名称的情况下将配置注入到每个位置,并且可以使用接口进行静态检查。

您当然可以分离接口和常数,以便能够在生产和开发中提供不同的值。

+2

适用于已知的静态值。我很好奇,如果我能告诉Angular使用构造函数(坚持模式)来实例化运行时确定的服务。 – gt6707a

+0

那么,那是一个普通的服务。只是不要称之为服务,并在这里你去:) –

+0

更新!在Angular4中,OpaqueToken已被弃用,并将被替换为InjectionToken。 InjectionToken允许传递一个泛型类型参数。 1)https://stackoverflow.com/questions/41289264/what-is-in-angular-2-opaque-token-and-whats-the-point 2)https://arturas.smorgun.com /2017/06/08/inject-environment-configuration-into-service-in-angular4.html – WRDev