角呼叫服务功能作为参数

时间:2018-12-14 07:23:11

标签: angular

我对数据进行了简单的http请求,并构建了一个通用请求函数来处理组件上的相同操作。但是当我传递服务函数并将回调作为参数传递给通用函数时,出现错误“无法读取未定义的属性'http'”。打击就是一个例子:

add(name: string): void {
    const newHero: Hero = { name } as Hero;

    //right
    // this.heroesService.addHero(newHero)
    //   .subscribe(hero => this.heroes.push(hero));

    //get error
    this.action(newHero
      , this.heroesService.addHero
      , hero => this.heroes.push(hero));
  }

  private action(request: any, requestMethod, callBack) {
    requestMethod(request).subscribe(callBack);
  }

服务代码:

import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class HeroesService {
  heroesUrl = 'api/heroes';  // URL to web api
  private handleError: HandleError;

  constructor(
    private http: HttpClient,
    httpErrorHandler: HttpErrorHandler) {
    this.handleError = httpErrorHandler.createHandleError('HeroesService');
  }

  addHero (hero: Hero): Observable<Hero> {
    return this.http.post<Hero>(this.heroesUrl, hero, httpOptions)
      .pipe(
        catchError(this.handleError('addHero', hero))
      );
  }
}

此错误在https://stackblitz.com/angular/oemgblxrqjy处得到证明

3 个答案:

答案 0 :(得分:0)

您的操作只有两个参数。 heroesService.addHero()在您的服务中注册为“可观察”。

    add(name: string): void {
    const newHero: Hero = { name } as Hero;

    //right
    // this.heroesService.addHero(newHero)
    //   .subscribe(hero => this.heroes.push(hero));

    // action method has only 2 parameters.
    this.action(this.heroesService.addHero(newHero)
      , hero => this.heroes.push(hero));
   }

  private action(request: any, requestMethod, callBack) {
    requestMethod(request).subscribe(callBack);
  }

答案 1 :(得分:0)

问题出在#addHero的{​​{1}}上下文中。

如果仍然要使用this方法,请尝试使用此方法:

#action

答案 2 :(得分:0)

通话时

this.action(newHero
  , this.heroesService.addHero
  , hero => this.heroes.push(hero));

this.heroesService中的“ this”未指向服务实例。这就是为什么它无法获取this.http。

如果将方法调用与this.heroesService(服务实例)绑定,则“ this”指向正确的实例。您可以使用以下代码段。

this.action(newHero
  , this.heroesService.addHero.bind(this.heroesService)
  , hero => this.heroes.push(hero));
相关问题