【发布时间】:2018-03-14 23:10:51
【问题描述】:
抱歉,如有重复,我已阅读相关帖子,但没有找到(或不理解)答案。
我有一个被许多组件使用的服务,我希望它成为所有组件(在所有应用程序中)的单例。 该服务必须发送一次请求并获取一次数据,然后在其他组件之间共享该数据。
下面是一些代码示例:
app.module.shared.ts
import { MyService } from '../services/myservice';
@NgModule({
declarations: [
//...
],
imports: [
//...
],
providers: [
MyService
]
})
myservice.ts
@Injectable()
export class MyService {
shareData: string;
constructor(private http: Http, @Inject('BASE_URL') private baseUrl: string) { }
getSharedData(): Promise<string> {
return new Promise<string>(resolve => {
if (!this.shareData) {
this.http.get(this.baseUrl + "api/sharedDara").subscribe(result => {
this.shareData = result.json() as string;
resolve(this.shareData);
}, error => console.log(error));
} else {
resolve(this.shareData);
}
});
}
}
example.component.ts(使用示例)
import { MyService } from '../services/myservice';
@Component({
selector: 'example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit {
sharedData: string;
public constructor(private myService: MyService,
@Inject('BASE_URL') private baseUrl: string) { }
ngOnInit() {
this.myService.getSharedData().then(result => this.sharedData= result);
}
}
依赖是注入器范围内的单例。
据我了解,每个组件都会创建自己的服务实例。这样对吗?以及如何为所有组件创建一个服务实例?
提前致谢。
【问题讨论】:
-
@Vega 在我的 /@NgModule 中我在提供程序中注册了服务(上面的代码),但是请求发送的次数与服务注入其他组件的次数一样多。这样我假设为每个组件创建服务实例
-
这样是单例的。如果你想创建多个实例,你可以通过在组件级别而不是模块级别添加提供来做到这一点
-
@AniruddhaDas 但是服务的构造函数被调用了两次并且请求被发送了三次(但我真的希望它被发送一次)。没事吧?
标签: angular typescript dependency-injection