Search code examples
jsonangularangular2-http

Get contents of json file not working


I want to get a json object from a json file using angular 2 http.get. What I end up getting from the file is this:

t_isScalar: falseoperator: tsource: t__proto__: Object

Here is my code

@Injectable()
export class ValidateJSONSchemaService {

    constructor(private http: Http) { }

    getSchema(fileName): any {
        return(this.http.get(fileName)
            .map(this.extractData)
        );
    }

    private extractData(res: Response) {
        let body = res.json();
        return body.data || {};
    }
}

How do I fix getSchema to make it return the json object rather than this: t_isScalar: falseoperator: tsource: t__proto__: Object. Note that when I change the file name it returns the same thing. I would have expected an informational error (I did do error handling but the code never errors out).


Solution

  • You need to subscribe to observable:

    @Injectable()
    export class ValidateJSONSchemaService {
    
        constructor(private http: Http) { }
    
        getSchema(fileName): any {
            return(this.http.get(fileName)
                .map(this.extractData).subscribe(data => console.log(data));
            );
        }
    
        private extractData(res: Response) {
            let body = res.json();
            return body.data || {};
        }
    }