【问题标题】:Property JSON does not exist on type Object类型 Object 上不存在属性 JSON
【发布时间】:2020-09-02 12:11:35
【问题描述】:

我正在尝试读取这样的 JSON 配置文件

this.http.get('assets/env/env.json').pipe(map( res => res.json())).pipe(catchError((error: any): any => {
  console.log('Configuration file "env.json" could not be read');
  
  return Observable.throw(error.json().error || 'Server error');
})).subscribe( (envResponse) => {
  endpoint="conf-" + envResponse.env + ".json";
  alert(endpoint);
});

但是 res.json() 显示为错误

我正在导入这些类

import { Injectable } from '@angular/core';
import { HttpClient, HttpBackend } from '@angular/common/http';
import { map, catchError } from 'rxjs/operators';
import { Observable } from 'rxjs';

你能指出我做错了什么吗?

我的是 9 角

【问题讨论】:

标签: angular angular9


【解决方案1】:

我相信您来自旧版本的 Angular/RxJS。在较新的版本中,默认的responseTypejson。所以res.json() 不再需要了。

试试下面的

this.http.get('assets/env/env.json').pipe(
  catchError((error: any): any => {...})
).subscribe(
  ...
);

此外,您不需要为每个 RxJS 运算符单独使用 pipe()。您可以将所有运算符包含在一个管道中。

this.http.get('assets/env/env.json').pipe(
  map(res => {
    // transform and return the value
  }),
  tap(res => {
    // perform some side-effects
  }),
  catchError((error: any): any => {
    console.log('Configuration file "env.json" could not be read');
    return throwError(error.error || 'Server error');
  })
).subscribe(
  ...
);

现在还有一个 RxJS throwError 函数而不是 Observable.throw

【讨论】:

    【解决方案2】:

    您也可以将您的 compilerOptions 设置为

    ,而不是使用 http 来检索 json
        "resolveJsonModule": true,
        "allowSyntheticDefaultImports": true
    

    并在你的 ts 文件中导入 json

    import myJson from './path-to-json/my-json.json';
    

    然后您可以像常量(同步)一样访问它,无需资产或异步 http 调用。


    编辑:

    按照您的要求,这里会是什么样子

    首先你的导入(正确的路径应该不同)

    import envJson from '../env/env.json';
    

    那么你可以这样使用它:

      endpoint = "conf-" + envJson.env + ".json";
    

    请记住,这些 compilerOptions 默认情况下未启用,并且是执行此方法所必需的。


    请参考工作中的stackblitz:https://stackblitz.com/edit/angular-ivy-umoflb?file=src/app/app.component.ts (还要检查 tsconfig.ts 文件中添加的 compilerOptions)

    【讨论】:

    • 如果我这样导入,您能否解释一下如何从 JSON 配置文件访问属性?
    • 当我尝试这个时出现错误找不到模块'../../assets/env/conf.json'。考虑使用“--resolveJsonModule”导入扩展名为“.json”的模块
    • 是的,这正是我在回答中首先提到的。您需要启用此 compilerOption。
    • 那是我在 tsconfig.json 中启用的。 “resolveJsonModule”:真,“allowSyntheticDefaultImports”:真,
    • 也许您的项目中有另一个 tsconfig 文件覆盖了配置?我添加了一个堆栈闪电战。
    猜你喜欢
    • 2018-06-25
    • 2020-07-13
    • 1970-01-01
    • 1970-01-01
    • 2018-05-27
    • 2016-02-28
    • 1970-01-01
    • 1970-01-01
    • 2019-03-16
    相关资源
    最近更新 更多