2016-07-14 3 views
0

영웅 앱으로 Angular 2 튜토리얼을 진행 중입니다. 나는이 튜토리얼의 Http 부분에있다. 나는 아래 heroes.components.ts에서 반환 된 데이터를 사용하기 위해 노력하고있어 hero.service.tsAngular 2 then promise

getHeroes(): Promise<Hero[]> { 
    return this.http.get(this.heroesUrl) 
       .toPromise() 
       .then(response => response.json().data) 
       .catch(this.handleError); 
    } 

그 다음에 다음과 같은 방법으로 서버에 호출이 있습니다

(link)하지만 나는 그때 제대로 기능을 구현할 수 없습니다. 내가 this.heroes제목을 CONSOLE.LOG 수없는 이유는

EXCEPTION: Error: Uncaught (in promise): TypeError: this is null

export class HeroesComponent implements OnInit { 

title = 'Tour of Heroes'; 
heroes: Hero[]; 
selectedHero: Hero; 

constructor(
    private router: Router, 
    private heroService: HeroService) { } 

getHeroes() { 
    this.heroService.getHeroes().then(function(value) { 
     //SUCCESS 
     console.log(value); //this is working 
     this.heroes = value; //this is not working 
     console.log("I am inside then SUCCESS") 
     console.log(title); 
     console.log(this.heroes); 

    }, function(error) { 
     //FAILURE 
     console.log(error); 
    }) 

} 

ngOnInit() { 
    this.getHeroes(); 
} 

당신은 알고 계십니까이 콘솔 오류는 무엇입니까?

답변

4

범위을 피하기 위해 굵은 화살표 표기법을 사용하는 것이 좋습니다. 귀하의 경우, 은 클래스 인스턴스를 가리 키지 않고 약속의 sucesscallback을 가리 킵니다.

getHeroes() { 
    let instance : HeroesComponent = this; 
    this.heroService.getHeroes().then((value) => { 
     //SUCCESS 
     console.log(value); 
     this.heroes = value; 
     console.log("I am inside then SUCCESS") 
     console.log(this.title); 
     console.log(this.heroes); 

    }, (error) => { 
     //FAILURE 
     console.log(error); 
    }) 
} 
0

당신은 아마도 어떤 범위 지정 문제를 실행하고 있습니다 ...이 것은 찾고있는이 생각은 당신이 생각하는 것이 아닙니다. 이 같은 somehting을 시도해보십시오

getHeroes() { 
    let that = this; // use that now in all sub functions 
    this.heroService.getHeroes().then(function(value) { 
     //SUCCESS 
     console.log(value); //this is working 
     this.heroes = value; //this is not working 
     console.log("I am inside then SUCCESS") 
     console.log(that.title); 
     console.log(that.heroes); 

    }, function(error) { 
     //FAILURE 
     console.log(error); 
    }) 

} 
1

그것은 범위 많은 문제가있다 에, 타이프 라이터범위 문제 때 람다 함수와 함께, 귀하의 경우, JQuery와, 또는 다른 자바 스크립트 API에 대한 코드를 전달합니다. 변수의 범위를 저장하면 에 필요로하는 문제를 해결하려면, 그것은 예약 키워드이기 때문에, 당신의 범위를 저장 _this 를 사용하지 마십시오 :

getHeroes() { 
    let instance : HeroesComponent = this; 
    this.heroService.getHeroes().then(function(value) { 
     //SUCCESS 
     console.log(value); //this is working 
     instance.heroes = value; //this now works 
     console.log("I am inside then SUCCESS") 
     console.log(title); 
     console.log(instance.heroes); 

    }, function(error) { 
     //FAILURE 
     console.log(error); 
    }) 

} 

매우 중요한 참고은 Typescript에서 같은 일을하지만 자동으로 사용하므로 주석 처리 된 경우에는 불행하게도 작동하지 않습니다.

1

답장을 보내 주셔서 감사합니다. 범위 문제였습니다.

You might want to consider fat arrow notation to avoid scope conflicts. In your case, this does not point to the class instance but to the sucesscallback of your promise instead.

나는 굵은 화살표 표기법을 사용하여 문제를 해결했습니다.