首页 > 解决方案 > 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 方法,但这感觉就像是冗余代码。

标签: angular

解决方案


推荐阅读