programing tip

로컬 .json 파일을 읽는 Angular 5 서비스

itbloger 2020. 11. 4. 07:44
반응형

로컬 .json 파일을 읽는 Angular 5 서비스


Angular 5를 사용하고 있으며 angular-cli를 사용하여 서비스를 만들었습니다.

내가하고 싶은 것은 Angular 5의 로컬 json 파일을 읽는 서비스를 만드는 것입니다.

이것이 내가 가진 것입니다 ... 조금 붙어 있습니다 ...

import { Injectable } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

@Injectable()
export class AppSettingsService {

  constructor(private http: HttpClientModule) {
    var obj;
    this.getJSON().subscribe(data => obj=data, error => console.log(error));
  }

  public getJSON(): Observable<any> {
    return this.http.get("./assets/mydata.json")
      .map((res:any) => res.json())
      .catch((error:any) => console.log(error));

  }

}

이 작업을 완료하려면 어떻게해야합니까?


먼저 주입해야 HttpClient하지 HttpClientModule, 당신은 제거해야 두 번째 것은 .map((res:any) => res.json())새로운이 때문에 더 이상 필요하지 않습니다 HttpClient당신에게 기본적으로 응답의 몸을 줄 것이다, 마지막으로 당신이 가져올 수 있는지 확인 HttpClientModule당신에 AppModule:

import { HttpClient } from '@angular/common/http'; 
import { Observable } from 'rxjs/Observable';

@Injectable()
export class AppSettingsService {

   constructor(private http: HttpClient) {
        this.getJSON().subscribe(data => {
            console.log(data);
        });
    }

    public getJSON(): Observable<any> {
        return this.http.get("./assets/mydata.json");
    }
}

이것을 컴포넌트에 추가하려면 :

@Component({
    selector: 'mycmp',
    templateUrl: 'my.component.html',
    styleUrls: ['my.component.css']
})
export class MyComponent implements OnInit {
    constructor(
        private appSettingsService : AppSettingsService 
    ) { }

   ngOnInit(){
       this.appSettingsService.getJSON().subscribe(data => {
            console.log(data);
        });
   }
}

json을 직접 가져 오는 대체 솔루션이 있습니다.

컴파일하려면,이 모듈을 typings.d.ts 파일에 선언하십시오.

declare module "*.json" {
    const value: any;
    export default value;
}

코드에서

import { data_json } from '../../path_of_your.json';

console.log(data_json)

Angular 7의 경우 다음 단계에 따라 json 데이터를 직접 가져 왔습니다.

tsconfig.app.json에서 :

추가 "resolveJsonModule": true"compilerOptions"

서비스 또는 구성 요소에서 :

import * as exampleData from '../example.json';

그리고

private example = exampleData;

웹 서버에서 파일을 읽는 대신 로컬 파일을 실제로 읽는 방법을 찾을 때이 질문을 발견했습니다.이 파일을 "원격 파일"이라고 부르고 싶습니다.

그냥 전화주세요 require:

const content = require('../../path_of_your.json');

Angular-CLI 소스 코드는 저에게 영감을주었습니다. templateUrl속성 template과 값을 require실제 HTML 리소스 에 대한 호출로 대체하여 구성 요소 템플릿이 포함되어 있음을 알게되었습니다 .

AOT 컴파일러를 사용하는 경우 다음을 조정하여 노드 유형 정의를 추가해야합니다 tsconfig.app.json.

"compilerOptions": {
  "types": ["node"],
  ...
},
...

import data  from './data.json';
export class AppComponent  {
    json:any = data;
}

자세한 내용은이 기사를 참조하십시오 .


이 시도

서비스에 코드 작성

import {Observable, of} from 'rxjs';

json 파일 가져 오기

import Product  from "./database/product.json";

getProduct(): Observable<any> {
   return of(Product).pipe(delay(1000));
}

구성 요소에서

get_products(){
    this.sharedService.getProduct().subscribe(res=>{
        console.log(res);
    })        
}

JSON 파일을 만들어 보겠습니다. 이름을 navbar.json으로 지정하고 원하는대로 이름을 지정할 수 있습니다!

navbar.json

[
  {
    "href": "#",
    "text": "Home",
    "icon": ""
  },
  {
    "href": "#",
    "text": "Bundles",
    "icon": "",
    "children": [
      {
        "href": "#national",
        "text": "National",
        "icon": "assets/images/national.svg"
      }
    ]
  }
]

Now we’ve created a JSON file with some menu data. We’ll go to app component file and paste the below code.

app.component.ts

import { Component } from '@angular/core';
import menudata from './navbar.json';

@Component({
  selector: 'lm-navbar',
  templateUrl: './navbar.component.html'
})
export class NavbarComponent {
    mainmenu:any = menudata;

}

Now your Angular 7 app is ready to serve the data from the local JSON file.

Go to app.component.html and paste the following code in it.

app.component.html

<ul class="navbar-nav ml-auto">
                  <li class="nav-item" *ngFor="let menu of mainmenu">
                  <a class="nav-link" href="{{menu.href}}">{{menu.icon}} {{menu.text}}</a>
                  <ul class="sub_menu" *ngIf="menu.children && menu.children.length > 0"> 
                            <li *ngFor="let sub_menu of menu.children"><a class="nav-link" href="{{sub_menu.href}}"><img src="{{sub_menu.icon}}" class="nav-img" /> {{sub_menu.text}}</a></li> 
                        </ul>
                  </li>
                  </ul>

참고URL : https://stackoverflow.com/questions/47206924/angular-5-service-to-read-local-json-file

반응형