I have an angular service that looks like:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class ApiService {
constructor(private http: HttpClient) {}
getDataHttp(): Observable<any> {
return this.http.get(
'http://localhost:4200' '/assets/data.json'
);
}
}
Running angular locally, this would retrieve the json file data.json
in the assets
directory.
Is it possible to do the same thing on Stackblitz? What would that url look like?
Edit: Stackblitz- https://stackblitz.com/edit/angular-ivy-zptuyp
CodePudding user response:
Yes, it is possible.
Give the path direct from assets, like this -
this.httpClient.get('assets/data.json');
See the working example here
Even you can use same way on local also.
CodePudding user response:
Since the file with data is already present in the project, it does not require any localhost or something. You will need that when you have an actual backend API fetching you the data you want. But since its just a file inside your application, you need not do that.
Also, if you are sure that you will have data in your application itself, rather than storing it as a json file, you can store it as const value and read it from wherever you want.
Please find it here in this stackblitz: https://stackblitz.com/edit/angular-ivy-d1ocqb?file=src/app/app.component.html