2017-10-06 103 views
0

我不知道如何表達這個意思,所以請原諒這個奇怪的標題。調用方法的參考

我正在嘗試將方法傳遞給typescript類的屬性,並且當調用該屬性時,將調用原始方法分配。

這是打字稿類,注意'getMethod'屬性。

export class PagingConfiguration{ 
    getMethod: any; 
    sortBy: string; 
    sortAsc: boolean; 

    constructor(getMethod: any, sortBy: string, sortAsc: boolean) { 
     this.getMethod = getMethod; 
     this.sortBy = sortBy; 
     this.sortAsc = sortAsc; 
    } 
} 

上面的類是用於我的尋呼服務。該服務需要該類的一個實例,並且可以執行'getMethod'屬性。

下面是代碼,通知之類的「的getData」方法:

import { Injectable } from '@angular/core'; 

import { PagingConfiguration } from '../models/paging-configuration' 

@Injectable() 
export class PagingService { 

    private pagingConfiguration : PagingConfiguration; 
    private currentPage: number; 

    addPager(pagingConfiguration : PagingConfiguration) : PagingService { 
     this.pagingConfiguration = pagingConfiguration; 
     this.currentPage = 1; 
     return this; 
    } 

    getData() { 
     return this.pagingConfiguration.getMethod({ currentPage: this.currentPage }); 
    } 

    getNextPage() { 
     this.currentPage += 1; 
     this.getData(); 
    } 


} 

最後,我有一個角狀的部件,在產生的尋呼服務。在組件的init中,分頁服務調用getData方法,該方法調用pagingConfig類的'getMethod'屬性。

下面是組件代碼

import { Component, OnInit } from '@angular/core'; 

import { User } from '../../models/user'; 
import { PagingConfiguration } from '../../models/paging-configuration'; 

import { UserService } from '../../services/user-service'; 
import { PagingService } from '../../services/paging-service'; 

@Component({ 
    selector: 'user-search', 
    templateUrl: './user-search.component.html', 
    styleUrls: ['./user-search.component.css'] 
}) 
export class UserSearchComponent implements OnInit { 
    users: User[] = []; 

    private pager: PagingService; 

    constructor(private userService: UserService, private pagingService: PagingService) { } 

    ngOnInit(): void { 
     this.pager = this.pagingService.addPager(new PagingConfiguration(this.loadUsers, 'Created', false)); 
     this.pager.getData(); 
    } 

    loadUsers(currentPage: number) { 
     this.userService.getUsers(currentPage).then(users => { 
      this.users = users 
     }); 
    }; 
} 

我的問題是,當實現getMethod屬性被調用時,它會執行組件類,這是正確的loadUsers - 然而,該方法使用this.userService的組件。

編輯

所以,我已經嘗試了在compoennt的實例綁定到實現getMethod電話,但似乎沒有工作。

getData() { 
    return this.pagingConfiguration.getMethod({self: this.pagingConfiguration.component, currentPage: this.currentPage }).bind(this.pagingConfiguration.component); 
} 
+0

...'上下文中執行。綁定(這)'? – jonrsharpe

+0

請你可以展開,不知道你的意思@jonrsharpe –

+1

可能重複[如何訪問正確的\'this \'回調內?](https://stackoverflow.com/questions/20279484/how-to-訪問正確的回調內部) – jonrsharpe

回答

0

更改loadUsers方法是:

loadUsers = (currentPage: number) => { 
    this.userService.getUsers(currentPage).then(users => { 
     this.users = users 
    }); 
}; 

帶箭頭函數的語法定義函數,該函數將在的UserSearchComponent