我試圖從 API 獲取資料,到目前為止,我可以在 controle.log 中獲取資料并使用 json 列印出來。但是,我無法從介面或類中獲取 id、name、...。我不知道為什么我不能得到它。有人有線索嗎?
我也嘗試過電影 [] 類而不是 IData[] 但它沒有產生任何差異。
export class MoviesService {
private showMovies = new Subject<IData[]>();
movies$ = this.showMovies.asObservable();
constructor(private http: HttpClient) { }
getServerData(){
this.http.get<IData[]>("https://medieinstitutet-wie-products.azurewebsites.net/api/products").subscribe((dataFromApi: IData[]) =>
this.showMovies.next(dataFromApi))
}
}
export class ShowmoviesComponent implements OnInit {
showMovies: IData [] = []
constructor(private service: MoviesService) { }
ngOnInit(): any {
this.service.movies$.subscribe((dataFromService: IData[]) => {
return this.showMovies = dataFromService,
console.log(dataFromService)
})
this.service.getServerData()
}
}
export class Movies{
id: string
name: string
description: string
price: string
imageUrl: string
year: string
added: string
productCategory: string
constructor(
id: string,
name: string,
description: string,
price: string,
imageUrl: string,
year: string,
added: string,
productCategory: string){
this.id = id
this.name = name
this.description = description
this.price = price
this.imageUrl = imageUrl
this.year = year
this.added = added
this.productCategory = productCategory
}
}
export interface IData{
id: string
name: string
description: string
price: string
imageUrl: string
year: string
added: string
productCategory: string
}
<div *ngFor="let m of showMovies">
{{ showMovies | json}}
</div>
uj5u.com熱心網友回復:
嘗試將您subject的替換為BehaviorSubject
此外,您以錯誤的方式使用 ngFor。它應該是:
<div *ngFor="let m of showMovies">
{{ m | json}}
</div>
最后,不要忘記取消訂閱您的 observables:在您的情況下,您可以take(1)根據需要使用第一個 ->
this.http.get<IData[]>("https://medieinstitutet-wie-products.azurewebsites.net/api/products").pipe(take(1).subscribe((dataFromApi: IData[]) =>
this.showMovies.next(dataFromApi))
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/439524.html
