1

when i need to access to this ,

but i found problem to give the value true to this.idHiden

like : this.idHiden = true the error :

TypeError: Cannot set property 'idHiden' of null

and the code

import { Component  , Output} from '@angular/core' ;
import { NgForm }     from '@angular/forms';
 import * as Datastore from 'nedb';

@Component({
  moduleId : module.id ,
  providers: [ ],
  templateUrl : 'info.component.html'
})

export class InfoComponent {
  selkName : any ;
  insertedSelk : any  ;
  idHiden : false ;

  selkValidate : number ;

  constructor(){
    this.selkName = '' ;
    this.insertedSelk =  [] ;
    this.selkValidate = 1 ;
    this.SelkFinde(this) ;

  }
  DeletSelk(id:number ){
    let db = new Datastore({filename : 'ComerceDB'});
    db.loadDatabase(function() {
      db.remove({ _id: id }, {}, function (err:any, numRemoved:any) {

        this.idHiden = true
        console.log(this.idHiden) ;
      });
    });


}
}
SAMSOL
  • 90
  • 2
  • 8
  • Possible duplicate of [Angular2 this is null in component](http://stackoverflow.com/questions/41666774/angular2-this-is-null-in-component) – seidme Jan 20 '17 at 12:02

1 Answers1

2
db.loadDatabase(function() {
  db.remove({ _id: id }, {}, function (err:any, numRemoved:any) {

should be

db.loadDatabase(() => {
  db.remove({ _id: id }, {}, (err:any, numRemoved:any) => {

otherwise this will point to the caller instead to the current class.

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 2
    There is also a `function` in the outer function (`loadDatabase`) – eko Jan 20 '17 at 11:23
  • 1
    Thanks, totally missed that. Had to skim through the code 3x, even after I saw your comment :D. Thanks for the hint! – Günter Zöchbauer Jan 20 '17 at 11:29
  • can you explain to me – SAMSOL Jan 20 '17 at 11:31
  • Not sure what to explain. If you use `this.xxx` inside a function, then that works only if `this.` actually points to where you expect. Even if you are using TypeScript, a language with classes, it's still JavaScript what you are working with (with some additional syntactic sugar), and in JS `this` by default points to the scope where it was called. When you pass the function to `loadDatabase` or `remove` then when it is called from there `this` will point to `loadDatabase` or `remove`, not `InfoComponent` – Günter Zöchbauer Jan 20 '17 at 11:38
  • ahh ok i found the solution `var that = this ` and use inside the object ...tank you all – SAMSOL Jan 21 '17 at 09:30
  • 1
    That's not necessary if you consequently use `()=>` – Günter Zöchbauer Jan 21 '17 at 10:49