0

How to create an instance of Point in that way:

let npoint = new Point();

Point's constructor requires an argument (differs), which should be injected.

import { DoCheck, KeyValueDiffers, KeyValueDiffer } from '@angular/core';

export class GsPoint {

  uuid: string;

  differ: any;
  constructor(private differs: KeyValueDiffers) {
    this.differ = this.differs.find({}).create();
  }

  ngDoCheck() {
    const change = this.differ.diff(this);
    if (change) {
      change.forEachChangedItem(item => {
        console.log('item changed', item);
      });
    }
  }
}
ael
  • 514
  • 9
  • 26

2 Answers2

1

What you describe is some kind of service locator. Generally I would not recommend using this approach because you are hiding the class dependencies from the caller and makes testing potentially harder.

If you still want to implement your way, check out this solution.

exeraph
  • 81
  • 1
  • 8
0

if it is an ordinary class (not a component or a directive) then you can not inject the KeyValueDiffers service like we do at Component level or at module level.

1.) You need to

  • add @Injectable() to GsPoint and

  • provide GsPoint like providers: [GsPoint ] in a component or NgModule.

When you then inject GsPoint somewhere, a KeyValueDiffers instance gets passed to GsPoint when it is instantiated by DI (before it is injected the first time).

2.) An alternative approach is to configure a custom injector like

constructor(private injector:Injector) { 
   let resolvedProviders = ReflectiveInjector.resolve([KeyValueDiffers]);
   let childInjector = ReflectiveInjector.fromResolvedProviders(resolvedProviders,this.injector);

  let myDiffer : KeyValueDiffers= childInjector.get(KeyValueDiffers);

}

This way myDiffer will be a KeyValueDiffers instance, instantiated by Angulars DI, and myDiffer will be injected to GSPoint when instantiated.

But if you want to do it in that way then in component or in service where ever you use this class you have to pass the this.myDiffer instance of KeyValueDiffers service. (Note:- KeyValueDiffers must be injected in that component from which you create the object of this GsPoint Class)

 import {KeyValueDiffers , Component  } from '@angular/core';
 import {GSPoint} from '../gspoint/gspoint.ts';

 @Component({
    'selector': 'app-sample',
    'templateUrl':'sample.html',
    'styleUrl': 'sample.css'   
  })
 export class Sample {

   constructor(private diff: KeyValueDiffers){

     }
 ngOnInit(){
     let gsPoint = new GSPoint(this.dff); // this is how you can create object
   }   

}

Sunny Goel
  • 1,982
  • 2
  • 15
  • 21