我正在尝试创建一个简单的页面,当我尝试在component.html中显示我的json文件时,我遇到了这个问题
这是json文件。
{
"example": {
"cat": [
{
"title": "title 1",
"href": "#cat0"
},
{
"title": "title 1",
"href": "#cat1"
},
{
"title": "title 1",
"href": "#cat1"
},
{
"title": "title 1",
"href": "#cat1"
},
{
"title": "title 1",
"href": "#cat1"
}
]
}
}这就是接口。
export interface menuExample {
example?:{
cat?:{
title: string,
href: string
}
}
}这是服务部。
export class serviceMenu {
info: menuExample= {};
cargada = false;
team: any[] = [];
constructor( private http: HttpClient) {
this.loadMenu();
}
private loadMenu() {
this.http.get('assets/json/file.json')
.subscribe( (resp: any[]) => {
this.cargada = true;
this.team = resp;
});
}
}这是html文件
<li *ngFor="let menudetails of serviceMenu.info.example?.cat" class="side-nav__item">
<a href="{{menudetails.href}}" class="side-nav__link">
<span>{{menudetails.title}}</span>
</a>
</li>然后我导入了我的文件,我做了所有的事情,但我不明白错误:S
ERROR Error: StaticInjectorError(AppModule)[HeaderComponent -> serviceMenu ]: StaticInjectorError(Platform: core)[HeaderComponent -> serviceMenu ]: NullInjectorError: No provider for serviceMenu !
只是我试着用一个NgFor来显示我的json,并显示标题和href,没有别的。有没有人可以帮我或者提供一个更好更简单的解决方案?非常感谢!
Estefa
发布于 2019-04-16 13:57:36
您需要在serviceMenu类中添加@Injectable(),在AppModule类中添加providers: [ serviceMenu ]
发布于 2019-04-16 14:00:22
您需要在appmodule或组件中添加服务
import {serviceMenu} from '<your service path>'
@Component({
selector: 'componentName',
templateUrl: './componentName.html',
providers: [serviceMenu]
})或者您也可以在appmodule.ts的providers部分添加您的服务
import {serviceMenu} from '<your service path>'
providers: [serviceMenu]发布于 2019-04-16 14:00:52
错误看起来你错过了AppModule中的providers。您需要在AppModule中添加服务
@NgModule({
declarations: [];
imports: [];
providers: [ serviceMenu ] // like this
})https://stackoverflow.com/questions/55701345
复制相似问题