一、@Injectable()
如果所创建的服务不依赖于其他对象,是可以不用使用 Injectable 类装饰器。但当该服务需要在构造函数中注入依赖对象,就需要使用 Injectable 装饰器。不过比较推荐的做法不管是否有依赖对象,在创建服务时都使用 Injectable 类装饰器。
例如,app.component.ts中引用服务Loading.ts:
app.componets.ts中
import {
Component, ElementRef, ViewChild} from '@angular/core';
import {
Loading } from './providers/Loading';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent{
@ViewChild('loading') loading: ElementRef;
constructor(
public _Loading: Loading) {
}
}
Loading.ts中
import {
Injectable} from '@angular/core';
@Injectable()
export class Loading {
}