【问题标题】:How to fetch json data in Angular 2+如何在 Angular 2+ 中获取 json 数据
【发布时间】:2017-09-12 16:10:38
【问题描述】:

我正在尝试显示一个列表,其中包含从本地 json 文件中获取的数据。这是我的服务到目前为止的样子。

category.service.ts

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';

@Injectable()
export class CategoryService {
  constructor(private _http: Http) { }

  getCategories() {
    return this._http.get('api/categories.json')
      .map((response: Response) => response.json())
      .do(data => console.log('All; ' + JSON.stringify(data)))
      .catch(this.handleError);
  }

  private handleError(error: Response) {
    console.log(error);
    return Observable.throw(error.json().error || 'Server error');
  }
}

这是我注入它的 Category Menu 组件到目前为止的样子

import { Component, OnInit } from '@angular/core';
import { CategoryService } from '../category.service';

@Component({
  selector: 'app-category-menu',
  templateUrl: './category-menu.component.html',
  styleUrls: ['./category-menu.component.css']
})
export class CategoryMenuComponent implements OnInit {
  errorMessage: string;
  commerceName= `El baratón`;
  categoryName = `Bebidas`;
  categories: any = 'Not assigned yet';
  hasMenu?= true;

  constructor(private _categoryService: CategoryService) { }


  ngOnInit() {
    return this._categoryService.getCategories()
      .subscribe(
        categories => this.categories = categories,
        error => this.errorMessage = error
      );
  }

}

现在,我在控制台中遇到的错误是 404。对于这个项目,我使用了 CLI 版本 1.0 和 src/api/categories.json 文件夹中的 categories.json 文件。

我在这里做错了什么?

【问题讨论】:

  • 如何发布带有上层“Run code sn-p”功能的代码块?

标签: javascript json angular http typescript


【解决方案1】:

将您的 api/categories.json 移动到 assets 文件夹,然后将 url 更改为

return this._http.get('/assets/api/categories.json')

【讨论】:

  • 这解决了它。谢谢 现在我不明白为什么以前的方法不起作用。你能提供一些进一步的解释吗?
  • Angular CLI 将提供包含所有资源的 assets 文件夹,它不会像 lite-server 那样提供所有项目内容。
  • 当然,一旦应用程序具有实时后端(针对本地 .json 文件进行测试是个好主意),请求将发送到服务器,它可能与托管 Angular 应用程序的服务器不同.如果您不确定,最好使用轻量级 json 服务器,例如 npm:json-server,它托管任意文件夹中的 .json 文件并在单独的进程中运行。它还允许读取和写入它们。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-08
  • 2017-11-06
  • 1970-01-01
  • 2017-05-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多