【问题标题】:Get data from json file in Angular 2从Angular 2中的json文件获取数据
【发布时间】:2017-07-15 08:12:45
【问题描述】:

我有一个 json 文件,我正试图通过 Angular 2 中的服务将此信息放入我的项目中。这是我的代码:

这是我的服务:

import { Injectable } from '@angular/core';
import { Http, Response} from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class RecordsService {

data: any;

  constructor(private http: Http) { }

  getRecords(id) {
 return this.http.get('../assets/data/03_data.json')
      .map(data => {
        this.data = data;
      }, err => {
        if (err) {
          return err.json();
        }
      });
  }

}

那是组件:

import { Component, OnInit } from '@angular/core';
import { RecordsService } from '../shared/services/records.service';

@Component({
  selector: 'app-content',
  templateUrl: './content.component.html',
  styleUrls: ['./content.component.css'],
  providers: [RecordsService]
})
export class ContentComponent implements OnInit {

  constructor(private recService: RecordsService) { }

  ngOnInit() {
  }

  getRecords(id) {
    this.recService.getRecords(id)
      .subscribe(data => {
      console.log(data);
      }, err => {
        console.log(err);
      });
  }

}

谁能帮我做错了什么。谢谢!

【问题讨论】:

    标签: json angular service get subscribe


    【解决方案1】:

    你没有在任何地方调用getRecords(),所以它根本不会被解雇。我们发现id 根本不应该是getRecords() 中的参数。所以调用OnInit中的方法:

    ngOnInit() {
       this.getRecords();
    }
    

    您还需要从响应中返回实际的 json,即 .json() 这样做:

    .map(data => {
       this.data = data.json();
       return data.json();
    }
    

    【讨论】:

      【解决方案2】:

      您需要从您的map 语句中返回一些内容:

      .map(data => {
              this.data = data;
              return data;
            }
      

      【讨论】:

      • 我的控制台又什么都没有了。 :(
      • 应该是data.json() ;)
      • @vesselinivanov 当您在开发者工具中检查您的网络选项卡时,您看到响应了吗?
      • @echonax nope 我没有看到对我的服务的响应。
      • @AJT_82 我在组件中调用了 getRecord():this.recService.getRecords(id)
      猜你喜欢
      • 2017-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多