1

i try to get some JSON Data from a local file in assets. I search with google and found different solutions, but nothing is working, like i want.

i add a service with follow code:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})

export class JSONService {
    public JSONArr: any;

    constructor(private http: HttpClient ) { }

    initJSON(path: string = "") { 
        this.JSONArr = this.getJSONArr(path);
        
        console.log("@ Service");
        console.log(path);
        console.log(this.JSONArr);
        // return this.JSONArr;
    }

    async getJSONArr( path: string = ""): Observable<any> {
        return this.http.get(path).subscribe(data => { 
            this.JSONArr = data;
            console.log(data);
        }
    }

    
}

the path is given from the app.component.ts the JSON look as follow

{
        "title": "Testtitle",
        "content": "Test Message"
}

My problem is: the console.log within the getJSONArr returns the data from the json correctly, but the console.log within the initJSON returns undefined

can anyone help me ?

1
  • simply put: in your code, getJSONArr returns a subscription Commented Feb 20, 2022 at 13:58

1 Answer 1

2

You do the wrong way there. because an HTTP request is async. So, your console.log will show undefined for this.JSONArr.

in your service, you can only:

async getJSONArr(path: string = ""): Observable<any> {
   return this.http.get(path);
}

and in your component, you need only subscribe method to get data from JSON file

Component.ts

this.yourService.getJSONArr(yourPath).subscribe((jsonData) => console.log(jsonData));
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.