Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NativeScript Schematics - singleton Service constructor getting called multiple times

Singleton Service constructor getting called multiple times in a nativescript-schematics code sharing project. Here is some important dependencies version from my 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"

I have tried providedIn: 'root' described in angular official docs and checking the singletonInstance as well. Constructor is getting called multiple times.

@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;
}

}

Do I need to use forRoot as we have app.module.ts and app.module.tns.ts ?

like image 286
Narendra Avatar asked Nov 25 '25 07:11

Narendra


1 Answers

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

Above code is enough. And you need import UserService in the controller, like

@import UserService from ...;
class MyController{
  constructor(private userService: UserService){}
}
like image 189
Nick Wang Avatar answered Nov 27 '25 00:11

Nick Wang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!