繁体   English   中英

类型对象上不存在属性 JSON

[英]Property JSON does not exist on type Object

我正在尝试读取这样的 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/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

除了使用 http 来检索 json,您还可以将 compilerOptions 设置为

    "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 默认情况下未启用,并且需要执行此方法。


请参阅工作堆栈闪电战: https ://stackblitz.com/edit/angular-ivy-umoflb?file = src/app/app.component.ts(另请检查 tsconfig.ts 文件中添加的 compilerOptions)

暂无
暂无

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

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