我正在做一个关于Angular的LinkedInLearning教程,我不明白为什么我的组件不能显示来自对象的数据。我可以记录对象并查看属性字段。我可以显示布尔值,但对象属性不可用。
这是我的组件代码
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ListingsService } from '../listings.service';
import { Listing } from '../types';
@Component({
selector: 'app-listing-detail-page',
templateUrl: './listing-detail-page.component.html',
styleUrls: ['./listing-detail-page.component.css']
})
export class ListingDetailPageComponent implements OnInit {
isLoading: boolean = true;
listing: Listing;
constructor(
private route: ActivatedRoute,
private listingsService: ListingsService,
) { }
ngOnInit(): void {
const id = this.route.snapshot.paramMap.get('id');
this.listingsService.getListingById(id!).subscribe(l=>{
this.listing = l;
console.log(l);
this.isLoading = false;
});
this.listingsService.addViewToListing(id!).subscribe(()=>console.log('Views Updated'));
}
}
这是我要显示的HTML:
<div class="content-box" *ngIf="!isLoading">
<p>This listing has been viewed {{listing.views}} {{isLoading}} times</p>
<a routerLink="/listings">
<button>Back</button>
</a>
<h2>Name {{ listing.name }}</h2>
<p>{{listing.description}}</p>
<p>${{listing.price}}</p>
<a routerLink="/contact/{{listing.id}}">
<button>Contact Seller</button>
</a>
</div>
<div class="content-box" *ngIf="isLoading">
<h3>Loading...</h3>
</div>
{{isLoading}}值显示良好,将在页面上正确显示TRUE或FALSE,但不会呈现任何对象属性。我可以控制台记录对象并获取所有属性。正如您在控制台日志中看到的,看起来我的对象被保存在一个数组中,但我不确定这是如何发生的,也不知道如何处理该项。
Page with visible {{isLoading}} but non-rendered object
当我console.log JSON.stringfy(l)时,我得到的是:
JSON.stringify of the object in the console
我试图从Angular组件中以HTML形式显示一个对象,但它不可见,即使它在控制台日志中可用。
以下是在“getListingById”方法中返回单个“listing”项的列表服务
import { Injectable } from '@angular/core';
import { Listing } from './types';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';
const httpOptions={
headers: new HttpHeaders({
'Content-Type': 'application/json',
})
};
@Injectable({
providedIn: 'root'
})
export class ListingsService {
constructor(
private http:HttpClient,
) { }
getListings():Observable<Listing[]>{
return this.http.get<Listing[]>('/api/listings');
}
getListingById(id:string):Observable<Listing>{
return this.http.get<Listing>(`/api/listings/${id}`);
}
addViewToListing(id:string):Observable<Listing>{
return this.http.post<Listing>(
`/api/listings/${id}/add-view`,
{},
httpOptions
)
}
}
如果我添加
tag and json pipe the object, I get the correct output:
<pre>{{listing | json}}</pre>
generates this on the page:
{
"id": "123",
"name": "guitar",
"description": "My Old Guitar, plays fine",
"price": 200,
"userId": "12345",
"views": 78
}
]