我正在做一個HTTP調用的返回數據分配給服務變量服務&。現在,當我嘗試訪問組件中的該服務變量時,它在控制檯中記錄爲未定義。然而,當我將日誌代碼放入服務本身時它會被記錄下來,但在組件中它不起作用。不能訪問組件的服務變量 - Angular2
下面是我的參考代碼:
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));
}
}
與您的代碼英雄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
@jonrsharpe,找你糾正'heroes'具有相同的數據。我實際上試圖訪問組件中的服務變量。我的意圖是在服務中進行單個HTTP調用並使用服務變量在多個組件(列表/詳細信息)中使用返回的數據。我試着做一些改變,但它不起作用,因爲我是angular2中的新手。 – Jamshed
在這種情況下,我建議嘗試一種不同的方法;分享您收集的數據的可觀察數據。我最近爲我的同事寫了這篇文章:http://blog.jonrshar.pe/2017/Apr/09/async-angular-data。html – jonrsharpe