我不知道如何用这句话来解释这个奇怪的标题。
我试图将方法传递给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();
}
}
最后,我有一个角度组件,用于生成分页服务。在组件的初始化时,调用服务调用getData方法,该方法调用' getMethod' pagingConfig类的属性。
这是组件代码
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 。 / p>
修改
所以,我试图将compoennt的一个实例绑定到getMethod调用,但似乎没有用。
getData() {
return this.pagingConfiguration.getMethod({self: this.pagingConfiguration.component, currentPage: this.currentPage }).bind(this.pagingConfiguration.component);
}
答案 0 :(得分:0)
将loadUsers方法更改为:
loadUsers = (currentPage: number) => {
this.userService.getUsers(currentPage).then(users => {
this.users = users
});
};
通过使用箭头函数语法定义函数,该函数将在UserSearchComponent的上下文中执行