Не удается получить доступ к локальным данным JSON в Angular 5 с помощью httpclient - PullRequest
0 голосов
/ 29 мая 2018

Когда я попытался получить доступ к локальным данным Json в angular 5 с помощью httpclient, не смог получить данные, но при попытке доступа к ним с помощью веб-сервера он работал.я добавил папку api в файл angular-cli.json и до сих пор не могу получить доступ к json.

employee.component.ts

    import {Component} from "@angular/core"

    import {EmployeeService} from './employee.service'

@Component({
  selector:'app-employee',
  templateUrl:'./employee.component.html'
})

export class EmployeeComponent {
         list:any
        data:any
   constructor(private employee:EmployeeService){}
     ngOnInit() {
       this.employee.getEmployee().subscribe(list=>{
      this.data= this.list.data
       console.log(this.list)
       })

     }
}

employee.service.ts

import {Injectable} from "@angular/core";
import {HttpClient} from "@angular/common/http";
import "rxjs/add/operator/map";

@Injectable()

export class EmployeeService {
    url: string = "src/app/api/employee.json"
    constructor(private http: HttpClient) {}

    getEmployee() {
       return this.http.get(this.url)
    }
}

employee.json

{
  "data": [
    {
      "id": 66896,
      "name":"Vinay",
      "phone": "9620529048",

      "address":{ 
        "city":"Bangalore",
        "street":"ABC street",
        "state":"Karnataka",
        "PostCode":"560076"
    }
    },
    {
      "id": 66923,
      "name":"John",
      "phone": "7720808609",

      "address":{ 
        "city":"Hyderabad",
        "street":"PQR street",
        "state":"UttarPradesh",
        "PostCode":"412114"
    }
    },
    {
      "id": 66898,
      "name":"Vijay",
      "phone": "8888830456",

      "address":{ 
        "city":"Pune",
        "street":"XYZ street",
        "state":"Maharastra",
        "PostCode":"411067"
    }
    }
  ]
}

путь к файлу json - src-> app-> api-> employee.json

Может кто-нибудь поделиться своими знаниями, чтобы яможет решить эту проблему

пожалуйста, найдите мой файл angular-cli.json

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "demo": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/demo",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [
              "src/app/api/employee.json",
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "demo:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "demo:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "demo:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.spec.json",
            "karmaConfig": "src/karma.conf.js",
            "styles": [
              "styles.css"
            ],
            "scripts": [],
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "src/tsconfig.app.json",
              "src/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "demo-e2e": {
      "root": "e2e/",
      "projectType": "application",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "demo:serve"
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": "e2e/tsconfig.e2e.json",
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    }
  },
  "defaultProject": "demo"
}

1 Ответ

0 голосов
/ 29 мая 2018

Посмотрите на angular-in-memory-web-api, он служит для имитации сервера данных, он перехватывает HTTP-запросы.Angular сделал отличный урок: https://angular.io/tutorial/toh-pt6

...