javascript - 如何在 Angular 2+ 中获取 json 数据

标签 javascript json angular http typescript

我正在尝试显示一个列表,其中包含从本地 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');
  }
}

这是我注入(inject)的类别菜单组件到目前为止的样子

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 文件。

我在这里做错了什么?

最佳答案

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

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

关于javascript - 如何在 Angular 2+ 中获取 json 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43444751/

相关文章:

json - 将map转换为json会在golang中给出很多整数

angular - TS2531 : Object is possibly 'null'

angular - ControlValueAccessor 类中的 writeValue 函数在 Angular 2 自定义组件中调用一次

javascript - 添加新 Controller 后 Angularjs 应用程序无法运行

javascript - 委托(delegate) Javascript 函数

javascript - java中将hashmaps转换为json的hashmap。当发送到jsp时,我用javascript解析它。但在 javascript 中解析不正确

Angular 6 - 错误类型错误 : Cannot read property 'value' of undefined

javascript - 确定圆使用的网格

javascript - 为什么我们使用 next() 函数?

json - 使用 Perl 模块 LWP::Authen::OAuth2 创建 Google Team Drive