angular2无法在angular2类中访问它

时间:2017-01-20 11:19:18

标签: angular typescript

当我需要访问时,

但我发现问题是将值赋予真 to this.idHiden

喜欢:this.idHiden = true 错误:

TypeError:无法设置属性' idHiden'为null

和代码

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


}
}

1 个答案:

答案 0 :(得分:2)

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

应该是

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

否则this将指向调用者而不是当前类。

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