我知道如何将服务注入组件(通过@Component),但是如何使用DI来传递组件之外的服务?
换句话说,我不想这样做:
export class MyFirstSvc {
}
export class MySecondSvc {
constructor() {
this.helpfulService = new MyFirstSvc();
}
}
export class MyThirdSvc {
constructor() {
this.helpfulService = new MyFirstSvc();
}
}
Run Code Online (Sandbox Code Playgroud) 我创建了AngularJS 2服务,并在2个不同的组件中使用它:App-Component&Sub-Component.每个输出属性'log'(一个字符串)我的服务.
StateService类:
@Injectable ()
class StateService {
public log : string;
static count : number = 0;
constructor () {
this.log = '';
StateService.count++;
this.writeToLog ('CREATED '+StateService.count+' at ' + new Date().toString());
}
public writeToLog (text : string) : void {
this.log += text + '\n';
}
}
Run Code Online (Sandbox Code Playgroud)
零件 :
@Component ({
selector : 'Sub-Component',
template : `<hr>
This is the Sub-Component !
<BR>
StateService Log :
<pre>{{ _stateService.log }}</pre>
<button (click)="WriteToLog ()">Write to log</button>
`,
providers : [StateService] …Run Code Online (Sandbox Code Playgroud) 我一直试图弄清楚(DI)依赖注入如何在Angular2中工作.每当我尝试将服务/或类注入到我的组件中时,我遇到了很多问题/问题.
从不同的googled文章,我需要providers: []在组件配置中使用,或者有时我需要@Inject()在我的构造函数中使用或直接注入bootstrap(app, [service])?我也看到一些文章要我@injectable装扮装饰.
例如:要注入Http,我只需要将import{Http}Http放在提供程序中,但对于FormBuilder,我需要@Inject()在构造函数中使用.
什么时候使用什么有什么经验法则?你能提供一些示例代码片段吗?谢谢 :-)
我很难找到在Angular2服务中使用observables的示例/指南的方式.有一些用于与EventEmitter绑定的html模板的东西,但这似乎不适合服务.
其中一个重要的驱动主题是远离Angular2中的Promise,但我似乎无法使新语法正确.
我在做什么
我很好,如果承诺是这个例子的最佳解决方案,但我想弄清楚Observable Way是什么.
我的服务:
/*DS Work on firebase Auth */
import {Injectable} from 'angular2/angular2';
@Injectable()
export class FirebaseAuth {
ref = new Firebase('https://myfirebase.firebaseio.com');
//check if user is logged in
getAuth(): any {
return this.ref.getAuth();
}
//register a new user
createUser(user: any): Promise<any> {
return new Promise((resolve, reject) => {
this.ref.createUser(user, function(error, userData) {
if (error) {
reject(error);
console.log('Error creating user:", error');
} else {
resolve(userData);
console.log('Successfully created …Run Code Online (Sandbox Code Playgroud)