【问题标题】:Can't access the service variable in component - Angular2无法访问组件中的服务变量 - Angular2
【发布时间】:2017-04-17 09:23:39
【问题描述】:

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

以下是我的参考代码:

hero.service

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));
  }
}

hero-list.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]);
  }
}

【问题讨论】:

  • 你为什么需要“gbl”(顺便说一句,这不是一个好名字),因为你可以访问订阅中与heroes相同的数据,回调参数?你能扩展一下“不起作用”吗?
  • @jonrsharpe,您说得对,heroes 具有相同的数据。我实际上是在尝试访问组件中的服务变量。我的意图是在服务中进行单个 HTTP 调用并通过使用服务变量在多个组件(列表/详细信息)中使用返回的数据。我尝试做一些改变,但它没有奏效,因为我是 angular2 的新手。
  • 在这种情况下,我建议尝试不同的方法;共享您收集的数据的可观察值。我最近实际上是为我的同事写的:blog.jonrshar.pe/2017/Apr/09/async-angular-data.html
  • @JayakrishnanGounder,我在上面的代码中已经分享了它。我可以访问可观察的服务,但不能访问服务变量。

标签: angular typescript angular2-routing angular2-services angular2-observables


【解决方案1】:

您的代码的问题是当您在映射中使用extractData this 变量不是您的服务实例,它被分配给http请求的映射器。

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

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

检查这个Plunker!!

希望这会有所帮助!

一些参考,取自typescript documentation

this 和箭头函数

在 JavaScript 中,这是一个在函数运行时设置的变量 叫。这使它成为一个非常强大和灵活的功能,但它 代价是必须始终了解 函数正在执行。这是出了名的令人困惑,尤其是 返回函数或将函数作为参数传递时。

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

【讨论】:

  • 非常感谢,这确实对我有用。如果您能指出箭头功能如何解决我的问题,我将不胜感激。再次感谢!!
  • @Jamshed,添加了一些参考,您可以在链接中阅读更多内容。添加在答案中。干杯!!
猜你喜欢
  • 2023-03-28
  • 2016-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-03
  • 1970-01-01
  • 2018-06-09
  • 2017-03-25
相关资源
最近更新 更多