简体   繁体   English

如何从 Angular 服务类返回示例 json 数据作为响应

[英]how to return sample json data in response from angular service class

How to return sample json data in response instead of calling actual API.如何在响应中返回示例 json 数据而不是调用实际的 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.我想在不实际调用后端 API 的情况下测试我的 UI 代码。我有从 UAT 捕获的响应数据我已将其添加到我的服务中并将 json 文件放在同一文件夹中。

     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.响应未定义。

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.要使用 HttpClient 访问本地 .json 文件,文件的位置必须包含在angular.json文件的assets属性中。 By default (in most cases), the src/assets folder will already be included.默认情况下(在大多数情况下), src/assets文件夹已经包含在内。

angular.json 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.因此,要么需要将 .json 文件放在src/assets文件夹中,要么将它们的源文件夹路径添加到assets属性中。

Folder structure文件夹结构

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

Then you could access them using the HttpClient like the following然后你可以使用 HttpClient 访问它们,如下所示

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM