ionic2를 사용하여 html보기에서 내 개체 세부 정보를 표시하는 데 문제가 있습니다. 다음은 cart.ts 파일에 올바른 값을 출력합니다 (당근 출력).
this.cart = resultsFromAPI
console.log(this.cart.vegetable);
그러나 뷰에서 출력하려고하면 더 이상 페이지를 볼 수 없습니다. 나는 오류 때문에 가정하고 있습니다.
<h2>{{cart.vegetable}}</h2>
객체 만 출력하면 헤더에 [object Object]가 표시됩니다.
<h2>{{cart}}</h2>
오류는 "정의되지 않은 '야채'속성을 읽을 수 없습니다."인 것 같습니다. ts에서는 읽을 수 있지만 뷰에서는 읽을 수 없습니까?
아래는 전체 TS 코드입니다.
cart:any;
ngOnInit(){
this.getPosts(this.category, this.limit);
}
getPosts(category, limit){
this.cartService.getPosts(category, limit).subscribe(response => {
this.cart = response.data.children;
console.log( this.cart.vegetable);
});
}
답변 : 아래 게시물을 따라 갔지만 통화 전에 반품을해야했습니다.
public getPosts$(category, limit) {
return this.cartService.getPosts(category, limit).map(response => {
this.cart = response.data.children;
};
}
비동기 API 호출을 수행하고 있기 때문에 사용하기 전에 사용 가능한지 확인해야합니다. 또한 API 응답을 async
파이프 를 통해 Observable로 직접 사용할 수 있습니다 .
<h2>{{(cart | async)?.vegetable}}</h2>
OP 편집의 경우 : 다음과 같이 쓸 수 있습니다 (fname 끝에있는 $는 스트림임을 의미합니다).
public getPosts$(category, limit) {
return this.cartService.getPosts(category, limit).map(response => {
return response && response.data && response.data.children;
};
}
과:
ngOnInit() {
this.getPosts$(this.category, this.limit).subscribe(cart => {
this.cart = cart;
}
}
과:
<h2 *ngIf="cart>{{cart.vegetable}}</h2>
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다