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?
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; } );
}
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