2017-11-01 1 views
0

데이터를 관찰 가능에서 속성으로 설정하려고합니다. 그러나 컴백에 대한 반응을 위해서는 시간이 필요합니다. 속성은 undefined으로 설정됩니다. 서버에서 클래스 속성으로 데이터를 설정하는 방법서버에서 클래스의 속성으로 데이터를 설정하십시오. 각도 2

ngOnInit() { 
    this.comics.getChar().subscribe((responses: Response) => this.data = responses[1].json().data.results); 
    this.comicsList = this.data; // gives undefined 
    console.log(this.comicsList); 
    } 

답변

1

비동기 함수가 어떻게 실행되는지 이해하지 못하고 있습니다.

이 라인 :

this.comics.getChar().subscribe((responses: Response) => this.data = responses[1].json().data.results); 

않는이 라인 진행 전에없는 "마침"여부에 관계없이

this.comicsList = this.data; // gives undefined 

첫번째 라인의 실행이 시작하고 다음 라인 바로 실행 첫 번째 마무리. 그것은 비동기 실행의 특성으로, 언제 완료 될지 모르기 때문에 의존하지 않는 다른 모든 요소는 계속 실행됩니다. 그러나이 경우, 두 번째 라인은 명시 적으로 반응에 따라 달라집니다, 그래서 당신은 당신의 응답을받은 후에 만 ​​실행되도록 당신은 그것을 설정해야합니다

this.comics.getChar().subscribe((responses: Response) => { 
    this.data = responses[1].json().data.results; 
    this.comicsList = this.data; 
}); 

이 당신이하지 않는, 약간의 중복 이 목록에 대한 두 개의 참조를 유지해야하는 이유가 있습니다. 구독에 직접 comicsList를 설정했을 것입니다.

this.comicsList$ = this.comics.getChar().map(responses => responses[1].json().data.results); 

를 내가이 데이터를 필요로 내 템플릿에, 나는 비동기 파이프 구독 것 : 나는 아마 그렇게 할 것이지만

, 나는이 작업을 수행 할 것입니다.

<div *ngFor="let comic of comicsList$ | async">{{ comic }}</div> 
관련 문제