3

在 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 ?

4

2 回答 2

2
@Injectable({  providedIn: 'root'})
export class UserService {
  constructor(private _http: HttpClient) {
  }
}

上面的代码就足够了。你需要在控制器中导入 UserService ,比如

@import UserService from ...;
class MyController{
  constructor(private userService: UserService){}
}
于 2019-01-09T02:36:37.027 回答
0

经过进一步调查后,我发现 Visual code intellisense 已从 .js 文件而不是 .ts 文件导入服务。因此,它进行了多个构造函数调用。我要补充一点,因为它可能对某人的调试有帮助。

于 2019-01-16T04:52:36.207 回答