angular - Angular 7:重用角度解析器服务功能
问题描述
我有一个 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 ”关键字在从外部组件调用时变得未定义,因为范围发生了变化。
调用此服务函数的最佳方法是什么,以使“ this ”关键字具有 ABCResolverService 类的所有属性?
解决方法:我现在使用的解决方法是在组件中再次定义 fetchA、fetchB 方法,但这感觉就像是冗余代码。
解决方案
推荐阅读
- python - 在 m2m_changed 信号中迭代对象
- react-native - 使用 react-native 导航时在顶部获得空白
- android - 我们在 React Native App for Android 中设置 http://localhost:8081/
- asp.net-mvc - Linux 上的 ASP.NET Core 与 itextsharp 的问题
- python - 使用 Tensorflow 构建 RNN。如何正确预处理我的数据集以匹配 RNN 的输入和输出形状?
- flask - 无法在本地网络中访问 Flask 应用程序
- django - Celery - 如何获取 shared_task 的任务 ID?
- macos - ubuntu 18.04.1 in paralles desktop on mac arrowkey down and up 异常
- python - Pandas 数据框 OrderedDict 提取数据
- amazon-web-services - Azure Databricks 是否安全地挂载 S3