programing

Angular 2의 http.get()을 사용하여 로컬 파일에서 JSON 콘텐츠를 로드합니다.

showcode 2023. 3. 6. 21:37
반응형

Angular 2의 http.get()을 사용하여 로컬 파일에서 JSON 콘텐츠를 로드합니다.

에 JSON 파일을 http.get()2번입니다.스택 오버플로우음음음같 뭇매하다

은 나의 ★★★★★★★★★★★★★★★★★★★★입니다.app.module.ts where I 내가 있는 곳import그 theHttpModule and the 및 그JsonModule부에서@angular/http:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule, JsonpModule } from '@angular/http';
import { RouterModule, Routes } from '@angular/router';

import { AppComponent } from './app.component';
import { NavCompComponent } from './nav-comp/nav-comp.component';
import { NavItemCompComponent } from './nav-comp/nav-item-comp/nav-item-comp.component';


@NgModule({
    declarations: [
        AppComponent,
        NavCompComponent,
        NavItemCompComponent
    ],
    imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        JsonpModule,
        RouterModule.forRoot(appRoutes)
    ],
    providers: [],
    bootstrap: [AppComponent]
})

export class AppModule { }

컴포넌트에서는import Http ★★★★★★★★★★★★★★★★★」Response부에서@angular/http. . Then I have a function called 그럼 저는 '나'라는 기능이 있습니다.loadNavItems(), 용 사 를 하 여 로 대 용 하 j 다 드 where로 try를합츠사 j path니 with텐 using경 to a상son를여 my i load콘http.get() 그 해 주세요.console.log()이이다.ngOnInit():

import { Component, OnInit } from '@angular/core';
import { Http, Response } from '@angular/http';

@Component({
    selector: 'app-nav-comp',
    templateUrl: './nav-comp.component.html',
    styleUrls: ['./nav-comp.component.scss']
})
export class NavCompComponent implements OnInit {

    navItems: any;

    constructor(private http: Http) { }

    ngOnInit() {
        this.loadNavItems();
    }

    loadNavItems() {
        this.navItems = this.http.get("../data/navItems.json");
        console.log(this.navItems);
    }
}

로컬 JSON 파일은 다음과 같습니다.

[{
        "id": 1,
        "name": "Home",
        "routerLink": "/home-comp"
    },
    {
        "id": 2,
        "name": "Über uns",
        "routerLink": "/about-us-comp"
    },
    {
        "id": 3,
        "name": "Events",
        "routerLink": "/events-comp"
    },
    {
        "id": 4,
        "name": "Galerie",
        "routerLink": "/galery-comp"
    },
    {
        "id": 5,
        "name": "Sponsoren",
        "routerLink": "/sponsoring-comp"
    },
    {
        "id": 6,
        "name": "Kontakt",
        "routerLink": "/contact-comp"
    }
]

콘솔에 오류가 없고 다음 출력만 표시됩니다.

여기에 이미지 설명을 입력하십시오.

HTML 템플릿에서 다음과 같은 항목을 루프하고 싶습니다.

<app-nav-item-comp *ngFor="let item of navItems" [item]="item"></app-nav-item-comp>

여기 Stack Overflow에서 찾은 솔루션으로 만들었는데 왜 작동하지 않는 거죠?

상대 경로 편집:

, 했을 때는../data/navItems.json스크린샷에서 nav-comp.component.ts 파일을 볼 수 있습니다.여기서 data라는 폴더에 있는 JSON 파일에서 상대 경로를 사용하여 JSON 콘텐츠를 로드합니다.뭐가 잘못됐나요?콘솔이 상대 경로에서 JSON 파일을 찾을 수 없기 때문에 404 오류를 출력합니까?

여기에 이미지 설명을 입력하십시오.

Angular 5+의 경우 1단계와 4단계만 수행합니다.


Angular 2+에서 로컬로 파일에 액세스하려면 다음(4단계)을 수행해야 합니다.

[1] 자산 폴더 내부에 .json 파일을 만듭니다(예: data.json).

[2] 프로젝트 내에서 angular.cli.json(Angular 6+의 angular.json)으로 이동하고 자산 배열 내에 (패키지 뒤에) 다른 개체를 넣습니다.json 객체)는 다음과 같습니다.

{ "data.json", "input": "./", "output": ".data/"}

angular.cli.json의 전체 예

"apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico",
        { "glob": "package.json", "input": "../", "output": "./assets/" },
        { "glob": "data.json", "input": "./", "output": "./assets/" }
      ],

data.json은 이전에 자산 폴더에 추가한 샘플 파일일 뿐입니다(파일 이름은 원하는 대로 지정할 수 있습니다).

[3] localhost 경유로 파일에 접속해 보겠습니다.이 주소는 http://localhost:your_port/assets/data.json 입니다.

보이면 뭔가 잘못 한 거야순서 #4로 넘어가기 전에 브라우저의 URL 필드에 입력하여 액세스 할 수 있는지 확인하십시오.

[4] 이제 GET 요청을 생성하여 .json 파일을 가져옵니다(전체 경로의 .json URL을 알고 있으므로 간단합니다).

 constructor(private http: HttpClient) {}
        // Make the HTTP request:
        this.http.get('http://localhost:port/assets/data.json')
                 .subscribe(data => console.log(data));

옷을 갈아입어야 한다

loadNavItems() {
    this.navItems = this.http.get("../data/navItems.json");
    console.log(this.navItems);
}

로.

loadNavItems() {
    this.navItems = this.http.get("../data/navItems.json")
                    .map(res => res.json())
                    .do(data => console.log(data));
                    // This is optional. You can remove the last line
                    // if you don't want to log the loaded JSON file 
                    // in the console.
}

★★★★★★★★★★★★★★★★★★this.http.getObservable<Response>응답을 원하는 게 아니라 내용을 원하는 거죠

console.log는 관찰 것을 에는 navItems가 되어 있기 때문에 입니다.Observable<Response>.

, 를 할 필요가 .asyncpipe.contractions

<app-nav-item-comp *ngFor="let item of navItems | async" [item]="item"></app-nav-item-comp>

이거 잘 될 거야.상세한 것에 대하여는, HTTP Client 의 메뉴얼을 참조해 주세요.

나만의 솔루션

는 새로운 i i i i i i i i i i i 。component라고 하는test음음음:

여기에 이미지 설명을 입력하십시오.

가 만든 도 있어요.test.json assets에서 작성한 angular cli중요):

여기에 이미지 설명을 입력하십시오.

이 모의는 다음과 같습니다.

[
        {
            "id": 1,
            "name": "Item 1"
        },
        {
            "id": 2,
            "name": "Item 2"
        },
        {
            "id": 3,
            "name": "Item 3"
        }
]

컴포넌트 내 ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★test,import를 밟다rxjs음음음같 뭇매하다

import 'rxjs/add/operator/map'

은 '이것'을 하기 때문입니다.map의 your your.responseJSON 컨텐츠를 취득해, 그 컨텐츠를 루핑 할 수 있습니다.ngFor모의 데이터를 로딩하는 방법은 다음과 같습니다.하였습니다.http get 이 .this.http.get("/assets/mock/test/test.json")map과 반응subscribe 후 에 합니다.items를 '루프'로 합니다.ngFor 집에서는template타입도 내보냅니다.전체 컨트롤러 코드는 다음과 같습니다.

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

export type Item = { id: number, name: string };

@Component({
  selector: "test",
  templateUrl: "./test.component.html",
  styleUrls: ["./test.component.scss"]
})
export class TestComponent implements OnInit {
  items: Array<Item>;

  constructor(private http: Http) {}

  ngOnInit() {
    this.http
      .get("/assets/mock/test/test.json")
      .map(data => data.json() as Array<Item>)
      .subscribe(data => {
        this.items = data;
        console.log(data);
      });
  }
}

내 는 그 안에 template:

<div *ngFor="let item of items">
  {{item.name}}
</div>

에 모의 추가하고 경로를 변경하여 자산 폴더 파일을 추가할 수 .json. (가져오기)도(가져오기)HTTP ★★★★★★★★★★★★★★★★★」Response컨트롤러에 접속합니다..module.ts(메인)는 다음과 .

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule, JsonpModule } from '@angular/http';


import { AppComponent } from './app.component';
import { TestComponent } from './components/molecules/test/test.component';


@NgModule({
  declarations: [
    AppComponent,
    TestComponent
  ],
  imports: [
    BrowserModule,
    HttpModule,
    JsonpModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

가장 간단한 방법은 file.json 파일을 폴더 자산 아래에 추가하는 것입니다.

.angular-cli.json 파일을 편집할 필요가 없습니다.

Service

@Injectable()
export class DataService {
  getJsonData(): Promise<any[]>{
    return this.http.get<any[]>('http://localhost:4200/assets/data.json').toPromise();
  }
}

Component

private data: any[];

constructor(private dataService: DataService) {}

ngOnInit() {
    data = [];
    this.dataService.getJsonData()
      .then( result => {
        console.log('ALL Data: ', result);
        data = result;
      })
      .catch( error => {
        console.log('Error Getting Data: ', error);
      });
  }

###추가:

이상적으로는 개발 환경에서만 사용하는 것이 좋기 때문에 방탄성을 위해 환경.ts 파일에 변수를 만듭니다.

export const environment = {
  production: false,
  baseAPIUrl: 'http://localhost:4200/assets/data.json'
};

그런 다음 http.get for URL을 바꿉니다.

environment.prod.ts 파일에는 프로덕션 API URL을 지정할 수 있습니다.

navItems.json 파일을 "assets" 폴더에 넣습니다.Angular는 자산 폴더 안을 보는 방법을 알고 있습니다.그래서 다음 대신:

loadNavItems() {
    this.navItems = this.http.get("../data/navItems.json");
    console.log(this.navItems);
}

경로를 단순하게 변경합니다.

loadNavItems() {
    this.navItems = this.http.get("assets/navItems.json");
    console.log(this.navItems);
}
  • 파일 JSON 파일 작성/이동assets

  • 어떤 방법을 사용하다.

    private URL = './assets/navItems.json'; // ./ is important!
    
    constructor(private httpClient: HttpClient) {
    }
    
    fetch(): Observable<any> {
        return this.httpClient.get(this.URL);
    }
    
  • 그것을 성분으로 부르다.

    private navItems: NavItems[];
    
    constructor(private navItemsService: NavItemsService) { }
    
    ngOnInit(): void {
      this.publicationService.fetch().subscribe(navItems => this.navItems = navItems);
    }
    

에 대한 을 " "에 navItems왜냐면http.get()관찰 가능한 것을 반환하므로 구독해야 합니다.

다음 예를 보겠습니다.

// Version without map
this.http.get("../data/navItems.json")
    .subscribe((success) => {
      this.navItems = success.json();
    });

// With map
import 'rxjs/add/operator/map'
this.http.get("../data/navItems.json")
    .map((data) => {
      return data.json();
    })
    .subscribe((success) => {
      this.navItems = success;
    });

「 」를 사용하고 Angular CLI: 7.3.3: 폴더에 가짜 JSON 후 상에 절차를 JSON 」 。

const API_URL = './assets/data/db.json';

getAllPassengers(): Observable<PassengersInt[]> {
  return this.http.get<PassengersInt[]>(API_URL);
}

여기에 이미지 설명을 입력하십시오.

언급URL : https://stackoverflow.com/questions/44042223/load-json-content-from-a-local-file-with-http-get-in-angular-2

반응형