无法访问组件中的服务变量 - Angular2

Jam*_*hed 2 typescript angular2-routing angular2-services angular2-observables angular

我正在服务中进行 HTTP 调用并将返回数据分配给服务变量。现在,当我尝试访问组件中的服务变量时,它在控制台中记录为未定义。但是,当我将日志代码放入服务本身时它会被记录,但在组件中它不起作用。

下面是我的代码供参考:

英雄服务

import { Injectable }              from '@angular/core';
import { Http, Response }          from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import { Hero } from './hero';

@Injectable()
export class HeroService {
heroes: Hero[];
hero: Hero;
gbl: Hero[];

  private heroesUrl = 'SERVICE URL';
  constructor (private http: Http) {}

  getHeroes(): Observable<Hero[]> {
    return this.http.get(this.heroesUrl)
                    .map(this.extractData)
                    .catch(this.handleError);
  }
  private extractData(res: Response) {
    let body = res.json()['data'];
    this.gbl = body;
    return body || { };

  }
  private handleError (error: Response | any) {
    Handles Error
  }

getHero(id: number): Observable<Hero> {
    return this.getHeroes()
      .map(heroes => heroes.find(hero => hero.id == +id));
  }
}
Run Code Online (Sandbox Code Playgroud)

英雄列表.component

import { Component } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { HeroService } from './hero.service';
import { Hero } from './hero';

@Component({
  template: `Template`
})

export class HeroListComponent {
  errorMessage: string;
  heroes: Hero[];
  listlcl: Hero[];
  id: number;
  public listheroes: Hero[];
  mode = 'Observable';
  private selectedId: number;

  constructor (
  private heroService: HeroService,
  private route: ActivatedRoute,
  private router: Router
  ) {}

  ngOnInit() { this.getHeroes() }
  getHeroes() {
  this.id = this.route.snapshot.params['id'];
  console.log(this.id);
    this.heroService.getHeroes()
                     .subscribe(
                       heroes => {
                       this.heroes = heroes;
                       this.listlcl = this.heroService.gbl;
                       console.log(this.listlcl);
                       },
                       error =>  this.errorMessage = <any>error);
  }

  isSelected(hero: Hero) { return hero.id === this.id; }

  onSelect(hero: Hero) {
    this.router.navigate(['/hero', hero.id]);
  }
}
Run Code Online (Sandbox Code Playgroud)

Mad*_*jan 5

您的代码问题是当您使用extractData内部地图this变量时,它不是您的服务实例,而是分配给 http 请求的映射器。

您可以简单地将您的函数转换为箭头函数,以便将范围设置为如下所示的服务实例,并且您将能够看到组件中的变量值,该值现在已正确分配给服务实例。

private extractData = (res: Response) => {
    let body = res.json()['data'];
    this.gbl = body;
    return body || { };    
  }
Run Code Online (Sandbox Code Playgroud)

检查这个Plunker

希望这可以帮助!!

一些参考,取自打字稿文档

this 和箭头函数

在 JavaScript 中,这是一个在调用函数时设置的变量。这使它成为一个非常强大和灵活的特性,但它的代价是始终必须知道函数正在执行的上下文。这是众所周知的混乱,尤其是在返回函数或将函数作为参数传递时。

我们可以通过在返回函数以供稍后使用之前确保函数绑定到正确的 this 来解决这个问题。这样,无论以后如何使用,它仍然可以看到原始的甲板对象。为此,我们将函数表达式更改为使用 ECMAScript 6 箭头语法。箭头函数在创建函数而不是在调用函数的地方捕获 this