http 호출을 할 때 들어오는 json을 구성 요소의 로컬 변수에 할당하고 뷰에 표시하려고합니다.HTTP : http 요청 후 로컬 변수가 정의되지 않음
서비스 :
getCases(){
return this.http.get('someUrl')
.map((res: Response) => res.json())
}
구성 요소 :
@Component({
template: `
<h1>Cases</h1>
<hr>
<br>
<table>
<tr *ngFor="let acase of cases" >
<td>{{acase.name}}</td>
</tr>
</table>
`,
})
export class CaseListComponent implements OnInit {
//local variable, need to have use of this!
acase: Case;
cases: Case[];
constructor(public _service: CaseService, public _route: ActivatedRoute) {
}
ngOnInit() {
this._service.getCases()
.subscribe(cases => this.cases = cases);
console.log(this.cases) // undefined!!
}
ngAfterContentInit() {
console.log("cases: ", this.cases) //undefined!
}
}
모두 괜찮습니다. 당신이 지적한 것을 놓친 것이 있습니까? 생성자에서 public을 private로 변경하십시오. – micronyks
매핑 끝 부분에 형식 지정자를 던져 볼 수도 있습니까? 다음과 같은 것 :'.map (res : Response) => res.json() as Case [])' –
이걸 시도해보십시오, getCases() : Observable { this.http.get ('someUrl') ... } ' – micronyks