我有一个Angular解析器服务,该服务被调用以在加载组件之前获取数据:
import {CustomService} from "path/to/custom/service";
@Injectable()
export class ABCResolverService {
constructor(private customService: CustomService) {
}
resolve(): Observable<any> {
return combineLatest(
this.fetchA(),
this.fetchB())
.pipe(map((data: any) => {
return data;
}));
}
fetchA(someParams?: string): Observable<any> {
/*..
code to develop params to pass
based on user's profile and other resolver configs
*/
return this.fetchA(someParams).pipe(map((data: any) => {
return data;
}));
};
fetchB(): Observable<any> {
return this.fetchB.pipe(map((data: any) => {
return data;
}));
};
}
在组件内部,我想再次调用fetchA()函数,并更改参数(例如分页参数,搜索文本参数等)
我通过以下方式调用组件内部的函数:
@Component({
selector: 'app-blah',
templateUrl: './blah.component.html',
styleUrls: ['./blah.component.scss']
});
export class ABCComponent implements OnInit {
constructor(private _abcResolverService: ABCResolverService) {}
ngOnInit() {}
customSearch(customParams){
/**
customParams calculation
*/
this._abcResolverService.fetchA(customParams)
.subscribe((data: any) => {
console.log('enjoy', data);
});
}
}
但是尝试在组件中重用此服务功能失败,并显示错误
Cannot read property fetchA of undefined
我了解这是因为从外部组件调用“ 此”关键字时未定义,因为范围发生了变化。
调用此服务函数的最佳方法是什么,以使“ this ”关键字具有ABCResolverService类的所有属性?
解决方法: 我现在使用的解决方法是再次在组件中定义fetchA和fetchB方法,但这就像冗余代码一样。