当我尝试"ng build --prod"
时,我的应用显示此错误:
src / app / app.component.html(1,7)中的ERROR:类型“ Hero []”上不存在属性“ title”。
但是我对"nodemon"
和"ng serve"
和"ng build"
没问题
我只对"ng build --prod"
有问题。
app.component.html
<router-outlet>
{{ heroes?.title }}
</router-outlet>
app.component.ts
import { Component, OnInit } from "@angular/core"
import { Hero, ConfigService } from "src/app/services/config/config.service"
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.scss"]
})
export class GoldHomeContentComponent implements OnInit {
heroes: Hero[]
error: any
constructor(private configService: ConfigService) {}
getHeroes(): void {
this.configService.getHeroes().subscribe(
heroes => (this.heroes = heroes) ,
error => (this.error = error)
)
}
ngOnInit() {
this.getHeroes()
}
}
config.service.ts
import { Injectable } from "@angular/core"
import { HttpClient , HttpHeaders } from "@angular/common/http"
import { Observable } from "rxjs"
export interface Hero {
title: string
}
const httpOptions = {
headers: new HttpHeaders({
"Content-Type": "application/json"
})
}
@Injectable({
providedIn: "root"
})
export class ConfigService {
heroesUrl = "/assets/data/config.json"
constructor(private http: HttpClient) {}
getHeroes(): Observable<Hero[]> {
return this.http.get<Hero[]>(this.heroesUrl, httpOptions)
}
}
assets/data/config.json
{
"title": "John Doe"
}
[UPDATE]
更改app.component.ts中的getHeroes()
getHeroes(): void {
this.configService.getHeroes().subscribe((data:any)=>{
this.heroes = [data]
// console.log(this.heroes = [data])
})
}
答案 0 :(得分:0)
根据代码,英雄看起来像一个数组,您需要具有 ngFor
来遍历元素
<li *ngFor="let hero of heroes">
{{ hero?.title }}
</li>
也将config.json更改为
[{
"title": "John Doe"
}]
如果只想绑定对象,则将代码更改为
heroes: Hero;
休息应该很好