서비스에서 응답 데이터를 할당하는 & 서비스에서 HTTP 호출을 만들고 있습니다. 이제 구성 요소에서 해당 서비스 변수에 액세스하려고하면 콘솔에 정의되지 않은 것으로 기록됩니다. 그러나 로그 코드를 서비스 자체에 넣었을 때 기록되지만 구성 요소에서는 로그 코드가 작동하지 않습니다. 다음은 구성 요소 - 각도 2에서 서비스 변수에 액세스 할 수 없습니다.
는 참조 용으로 내 코드입니다 : 당신이extractData
를 사용할 때
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"(위대한 이름은 아님)이 필요합니까? 구독에서 '영웅'과 같은 데이터, 콜백 매개 변수? 확장 할 수 있습니까 * "작동하지 않습니다"*? – jonrsharpe
@jonrsharpe, You'r는 '영웅들'이 동일한 데이터를 가지고 있다고 정정합니다. 실제로 구성 요소에서 서비스 변수에 액세스하려고합니다. 내 의도는 서비스에서 단일 HTTP 호출을 만들고 서비스 변수를 사용하여 여러 구성 요소 (목록/세부 정보)에서 반환 된 데이터를 사용하는 것입니다. 나는 약간의 변화를 시도했지만 angular2의 초보자로서 작동하지 않았다. – Jamshed
그런 경우 다른 방법을 시도하는 것이 좋습니다. 수집 한 데이터를 관찰 할 수 있습니다. 나는 최근에 나의 동료들에게 이것을 실제로 썼다 : http://blog.jonrshar.pe/2017/Apr/09/async-angular-data.html – jonrsharpe