简体   繁体   中英

How can i read json file?

I would like to read json file. But, when a read my const, it's empty.. Thanks a lot to your help

import { HttpClientModule, HttpClient } from '@angular/common/http';

@NgModule({
    imports: [
        HttpClientModule
    ]
})

   private url: string= './../../json/config.json';
   constructor(private http: HttpClient) {}

   const aaa = this.http.get(this.url);
   console.log('aaa', aaa)

   console.log === Observable {_isScalar: false, source: Observable, operator: MapOperator}
   operator: MapOperator {project: ƒ, thisArg: undefined}
   source: Observable {_isScalar: false, source: Observable, operator: FilterOperator}
   _isScalar: false
   __proto__: Object

I have consumed json files in my angular projects before. Mostly in spec files but here is an example. You can import (or require) your json file using its path relative to your code file.

import * as testData from './testing/probe.testdata.json';

and then consume the json data using your testData variable. like this:

const obj = (<any>testData);
var myJsonProp = obj.PropertyName;

this works for me, please be aware this eg is in typescript. but js works too. this would replace your call to this.http.get(this.url) good luck!

I use a class like this:

export class State {
    constructor(public id: number, public name: string) { }
}
export class City {
    constructor(public id: number, public name: string, public state) { }
}

export const states: State[] = [
    {
        id: 0,
        name: 'Alabama'
    },
    {
        id: 1,
        name: 'Alaska'
    }
...

Then in components:

import { State, states, City, cities } from '../../shared/classes/us-areas';
...
readonly states: State[] = states;
readonly cities: City[] = cities;

Then I can use the class:

console.log(this.user.cities);
console.log(this.user.states);

For JSON you can simply import the file or subscribe to its endpoint source and output it with Angular's JSON pipe.

<pre>{{newData | json}}</pre>

For serving JSON source data you could create a service and make a Subject which is subscribable from anywhere.

public post<T>(): Observable<any> {
    return this.http.get("https://example.com/config.json");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM