2017-10-06 67 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