0

I need to read the JSON file which we have stored locally in the project workspace, because I need to read the component.ts file.

Are there any basic steps?

0

2 Answers 2

0

You can read JSON data using HTTP request

getJsonData(){
    let jsonUrl = 'Your json file path';
    return this.http.get(jsonUrl)
      .map( (response: Response) => {
        const data = response.json();
        return data; } );
}
Sign up to request clarification or add additional context in comments.

2 Comments

If you're use http, you must "map" the respone and use response.json like @bipin patel shown If you use the new httpClient NOT use response.json. You have already the object directly
if it's work for you than tick right on my answer
0

It's simple. You can do directly in a component or using a service. It's better create a service to separate the logic of the application. (If in a future you'll want change the way to access to the data you only must to change the service)

Your service

@Injectable()
export class DataService {
    constructor(private http: HttpClient) { } //<-- inject HttpClient
    getData() {
        return this.http.get('../assets/data.json')
    }).catch(
        (error: Response) => {
        return Observable.throw(error);
    });
}

Your Component

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  constructor(private dataService:DataService){} //<--inject the service

  data:any //<--a variable
  ngOnInit(){
    this.dataService.getData().subscribe((data)=>
    {  
         this.data=data
    }
}

Remember, in your app.module declare the service

@NgModule({
   ...
   providers: [DataService,..]
}

Of course you can do all in the component, but it's disapproved

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.