【发布时间】: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