在 nativescript-schematics 代码共享项目中多次调用单例服务构造函数。这是我的 package.json 中的一些重要依赖版本:
"tns-android": {"version": "5.0.0"}
"@angular/core": "~7.1.0",
"nativescript-angular": "^7.1.0",
"tns-core-modules": "^5.0.5",
"@nativescript/schematics": "^0.4.0",
"nativescript-dev-typescript": "^0.7.8",
"nativescript-dev-webpack": "^0.17.0",
"typescript": "~3.1.1"
我已经尝试providedIn: 'root'
在Angular 官方文档中进行描述并检查了 singletonInstance 。构造函数被多次调用。
@Injectable({ providedIn: 'root'})
export class UserService {
constructor(private _http: HttpClient) {
if (!UserService.singletonInstance) {
console.log('in user service constructor');
UserService.singletonInstance = this;
} else {
return UserService.singletonInstance;
}
}
我需要使用forRoot吗,因为我们有 app.module.ts 和 app.module.tns.ts ?