4

How to return sample json data in response instead of calling actual API. I want to test my UI code without actually calling backend API .I have response data captured from UAT I have added this in my service and put json file in same folder.

     getdata(): Observable<any>{
return this.http.get<any>('keyinfoResponse.json')
.pipe(map((data)=>data),catchError((error)=>throwError(error)));

}

and in component

this.dataService.getdata().subscribe((response) => {
     
      this.keyInfoResponse = response;
    }, (error) => {
      this.hasErrorOccurred = true;      
      if (error.message) {
        this.errorMessage = error.message;
      }       
    });
  }

the response is undefined.

2
  • whats the issue ? Commented Nov 6, 2020 at 6:56
  • 1
    put the json in 'assets' folder, and change your url in the service to 'assets/keyinfoResponse.json' Commented Nov 6, 2020 at 7:05

1 Answer 1

2

To access a local .json file using the HttpClient, the location of the file must be included in the assets property of angular.json file. By default (in most cases), the src/assets folder will already be included.

angular.json

{
  ...
  "projects": {
    "site": {
      ...
      "architect": {
        "build": {
          ...
          "options": {
            ...
            "assets": [
              "src/assets"
            ],

So either need to place the .json files in the src/assets folder or if not, add their source folder path to the assets property.

Folder structure

src
├── app
├── assets
│   ├── keyinfoResponse.json
├── angular.json
├── index.html
...

Then you could access them using the HttpClient like the following

getdata(): Observable<any> {
  return this.http.get<any>('assets/keyinfoResponse.json').pipe(
    map((data) => data),
    catchError((error) => throwError(error))
  );
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.