1

서비스에서 응답 데이터를 할당하는 & 서비스에서 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]); 
    } 
} 
+0

왜 "gbl"(위대한 이름은 아님)이 필요합니까? 구독에서 '영웅'과 같은 데이터, 콜백 매개 변수? 확장 할 수 있습니까 * "작동하지 않습니다"*? – jonrsharpe

+0

@jonrsharpe, You'r는 '영웅들'이 동일한 데이터를 가지고 있다고 정정합니다. 실제로 구성 요소에서 서비스 변수에 액세스하려고합니다. 내 의도는 서비스에서 단일 HTTP 호출을 만들고 서비스 변수를 사용하여 여러 구성 요소 (목록/세부 정보)에서 반환 된 데이터를 사용하는 것입니다. 나는 약간의 변화를 시도했지만 angular2의 초보자로서 작동하지 않았다. – Jamshed

+0

그런 경우 다른 방법을 시도하는 것이 좋습니다. 수집 한 데이터를 관찰 할 수 있습니다. 나는 최근에 나의 동료들에게 이것을 실제로 썼다 : http://blog.jonrshar.pe/2017/Apr/09/async-angular-data.html – jonrsharpe

답변

4

문제입니다 내지도 this 변수가 서비스의 인스턴스가 아닙니다. , http 요청의 맵퍼에 지정됩니다.

당신은 단순히 기능을 Arrow 함수로 변환 할 수 있습니다. 범위가 아래처럼 서비스 인스턴스로 설정되고, 서비스 인스턴스에 올바르게 할당 된 컴포넌트의 변수 값을 볼 수 있습니다.

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

체크 this Plunker !!

희망이 도움이됩니다!

typescript documentation 찍은 일부 기준,

이 화살표 자바 스크립트 함수

,이 함수가 호출 될 때 가 설정되어 가변된다. 이것은 매우 강력하고 유연한 기능이지만, 함수는 함수가 실행되는 컨텍스트에 대해 항상 알 필요가 있습니다. 이것은 매우 혼란 스럽습니다. 특히 은 함수를 반환하거나 함수를 전달할 때 특히 혼란 스럽습니다. 논의.

나중에 사용할 함수를 반환하기 전에 함수가 올바른 에 바인딩되어 있는지 확인하여이 문제를 해결할 수 있습니다. 이 방법은 나중에 사용하는 방법과 관계없이 이며 원래의 데크 개체 인 을 계속 볼 수 있습니다. 이를 위해 함수 표현식을 으로 변경하고 ECMAScript 6 화살표 구문을 사용합니다. 화살표 함수는이 함수를 캡처합니다.

+0

정말 고마워요. 저에게 실제로 도움이 됐습니다. 화살표 기능이 내 문제를 해결하는 방법을 지적 할 수 있다면 정말 고맙겠습니다. 다시 한번 감사드립니다 !! – Jamshed

+0

@Jamshed, 몇 가지 참조를 추가하면 더 많은 링크를 읽을 수 있습니다. 대답에 추가했습니다. –

관련 문제