2016-04-27 24 views
6

ben şöyle bir kod vardır:Angular2 'bu' tanımsız

:

export class CRListComponent extends ListComponent<CR> implements OnInit { 

    constructor(
     private router: Router, 
     private crService: CRService) { 
     super(); 
    } 

    ngOnInit():any { 
     this.getCount(new Object(), this.crService.getCount); 
    } 

ListComponent kodu bu

@Component({}) 
export abstract class ListComponent<T extends Listable> { 

    protected getCount(event: any, countFunction: Function){ 
     let filters = this.parseFilters(event.filters); 
     countFunction(filters) 
      .subscribe(
       count => { 
        this.totalItems = count; 
       }, 
       error => console.log(error) 
      ); 
    } 

Ve CRService uygun hizmet kod parçası olan budur

getCount(filters) { 
    var queryParams = JSON.stringify(
     { 
      c : 'true', 
      q : filters 
     } 
    ); 

    return this.createQuery(queryParams) 
     .map(res => res.json()) 
     .catch(this.handleError); 
} 

ngOnInit() numaralı telefonum çalışırken hata mesajı alıyorum:

angular2.dev.js:23925 EXCEPTION: TypeError: Cannot read property 'createQuery' of undefined in [null]

ORIGINAL EXCEPTION: TypeError: Cannot read property 'createQuery' of undefined

Temel olarak, return this.createQuery(queryParams) ifadesindeki this deyiminde boş bırakılacaktır. Bunun nasıl olabileceği hakkında bir fikri olan var mı?

+1

Neden this.createQuery' var? –

+2

, 2 sınıfınızın bir kapatma ayracına sahip olmadığı "normal" midir? –

+0

Sadece gereksiz parçaları atladım, kod başka bir şekilde sözdizimsel olarak düzeltildi. :) Sorun '.createQuery' ile değil,' '' 'ile kendisi. – Sleeper9

cevap

7

Sorun burada bulunur:

gOnInit():any { 
    this.getCount(new Object(), this.crService.getCount); // <---- 
} 

Bir nesneye dışında bir işlev başvuru beri. bir ok fonksiyonu içine

this.getCount(new Object(), this.crService.getCount.bind(this.crService)); 

veya sar: Üzerinde bind yöntemi kullanabilirsiniz

this.getCount(new Object(), (filters) => { 
    return this.crService.getCount(filters)); 
}); 

İkinci yaklaşım tercih biri olacağını o türlerini sürmesine izin vermesinden dolayı. Daha fazla ayrıntı için bu sayfaya bakınız:

+0

Teşekkürler, işe yarıyor! Bunu HTML şablon bağlamalarında yapabileceğim bir yol var mı? Yani, şu kodum var: (onLazyLoad) = "loadItems ($ event, this.crService.getCRs)" ' Bunu da böyle bir şeye dönüştürebilir miyim? '(onLazyLoad) =" loadItems ($ olayı, (sayfa, n, sortField, sortOrder, filters) => {return this.crService.getCRs (sayfa, n, sortField, sortOrder, filters)}) "' – Sleeper9

+0

Harika! Şablonlardaki 'this' anahtar sözcüğünü kullanmanız gerekmez. Yani, bir orta seviye kullanırdım. Demek istediğim: this.crService.getCRs kullanarak 'loadItems' yöntemi ... –

+1

İyi, ben de bu çözüm ile sona erdi. Bu, HTML şablonlarında böyle çirkin kodları gömmekten de çok daha temiz görünüyor. Yardım için teşekkürler! :) – Sleeper9

2

Ben hataya neden benim fonksiyonun bütün iç organlar çekti ve başka bir işlevde attı Bu hatayı düzeltmek için daha sonra hata gitti. örnek

:

this.globalListenFunc = renderer.listenGlobal('document', 'click', (event) => { 
    this.evaluateClick(event); 
}); 

evaluateClick(evt: MouseEvent){ 
    // all the code I yanked out from above 
} 
: Ben dışarı kod çekti o

this.globalListenFunc = renderer.listenGlobal('document', 'click', (event) => { 
    // bunch of code to evaluate click event 
    // this is the code that had the "this" undefined error 
}); 

bazı kod ile bu işlevi vardı ve harici bir kamu görevi koymak

, burada bitmiş kod