Angular 4获取本地JSON文件

时间:2017-11-17 13:44:06

标签: json angular

我已经搜索了3个小时并且无法解决问题。所以我希望你们其中一个人知道如何解决它。我开发了

首先是代码:

import { Injectable } from '@angular/core';
import { OnInit } from '@angular/core/src/metadata/lifecycle_hooks';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class UserService {
  isLoggedIn: boolean;
  user: string[];
  constructor(private http: HttpClient) {
  }

  getData(): void {
    this.http.get('./src/assets/dummy-response/authentication/login.dummy.json').subscribe(data => {
      // Read the user infos  from the JSON response
      this.user = data['user'];
      console.log(data);
    });
    this.http.get('').subscribe(data => {
      // Read the login_success from the JSON response
      this.isLoggedIn = data['login_success'];
      console.log(data);
    },
  err => {
    console.log('ALARM');
  });
  }
}
console.log('HALLOOOO');

错误代码:

enter image description here

目录结构:

enter image description here

所以我的问题是,如何在assets / dummy-response / authentication / login.dummy.json中访问此文件? 我使用Angular的路由器,我想,这就是问题,他们不让我通过。

2 个答案:

答案 0 :(得分:2)

编译angular时,json的路径为

http://localhost:4200/src/assets/dummy-response/authentication/login.dummy.json

不是this.http.get('assets/dummy-response/authentication/login.dummy.json').subscribe(data => { // Read the user infos from the JSON response this.user = data['user']; console.log(data); });

所以你的获取请求需要如下:

iex

答案 1 :(得分:0)

试试这个:

var fs = require('fs');
var myData;

/* Read the file, and pass it to your callback*/
fs.readFile('./myjsondataFile.json', handleJSONFile);
var handleJSONFile = function (err, data) {
  if (err) {
     throw err;
 }
 myData= JSON.parse(data);
}