0

im new to typescript and angular 2 and what im trying to do is to create singletone to be used where ever is needed, but im getting this error:

Unexpected value 'ViewHelperComponent' declared by the module 'AppModule'

in the browser log, what am i doing wrong?

this is the class:

export class ViewHelperComponent {

static instance : ViewHelperComponent;

constructor() {}

public static getInstance(){
  if(ViewHelperComponent.instance == null)
     ViewHelperComponent.instance = new ViewHelperComponent();
  return ViewHelperComponent.instance;
}

check(){
  console.log("working");
}
}

and im calling it from this component:

import { Component} from '@angular/core';
import { ViewHelperComponent } from '../view-helper/view-helper';
@Component({
  selector: 'app-input-parent',
  templateUrl: './input-parent.component.html',
  styleUrls: ['./input-parent.component.css']
})
export class InputParentComponent implements OnInit {

temp : ViewHelperComponent;

constructor() {
  this.temp = ViewHelperComponent.getInstance()
}
}

2 Answers 2

1

There is no need to program a singleton manually. You need a singleton service, not a component, and Angular will do it for you if you'll just declare the provider for this service in the module. For example, you can create the following class:

class ViewHelper {

   check(){
      console.log("working");
  }
}

Declare it in the providers property of @NgModule:

@NgModule({ ...
   providers: [ViewHelper]
})

Now you can use it in any component:

@Component({
  selector: 'app-input-parent',
  templateUrl: './input-parent.component.html',
  styleUrls: ['./input-parent.component.css']
})
export class InputParentComponent implements OnInit {

 constructor(private viewHelper: ViewHelper) {
  this.viewHelper.check();
 }
}

If you declare the provider in @NgModule, Angular will create a singleton instance of it.

Sign up to request clarification or add additional context in comments.

Comments

0

Commonly In the app.module.ts file you need to bootstraping the 'ViewHelperComponent' in the @NgModule, for example:

@NgModule({ bootstrap: [ AppComponent ],
   declarations: [
         AppComponent,
         ViewHelperComponent]...

Greetings!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.