首页 > 解决方案 > 当我尝试以角度 2 显示 json(数组到对象中)时出现问题

问题描述

我尝试创建一个简单的页面,当我尝试在我的 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,仅此而已。有人可以帮助我或提供更好更简单的解决方案吗?非常感谢!

埃斯特法

标签: jsonangularobjectprovider

解决方案


您需要添加@Injectable()serviceMenu并添加providers: [ serviceMenu ]AppModule


推荐阅读