【问题标题】:Angular rxjs : force response to be null if http.get can't find the json fileAngular rxjs:如果 http.get 找不到 json 文件,则强制响应为空
【发布时间】:2020-07-03 04:41:33
【问题描述】:

在我的 Angular 应用中;我习惯于从静态 json 文件中获取数据;

像这样:

@Injectable()
export class ConfigService {
  constructor(private http: HttpClient) { }

  getData() { 
    this.http.get('/assets/myfile.json').subscribe(data => {
        console.log(data);
    })
  }

}

在某些场景中,myfile.json 可能不存在

(这是其他用途所需要的)

在这种情况下我不想得到这个错误

HttpErrorResponse : 解析期间的 Http 失败 https://localhost:4201/assets/myfile.json

但很简单,我想得到一个null response

建议??

【问题讨论】:

  • 您可以使用catchError() 并返回of(null) 或根据某些情况重新抛出错误。

标签: angular typescript ecmascript-6 rxjs


【解决方案1】:

如 cmets 中所述,您可以像这样使用 catchError 运算符:

getData() { 
    this.http.get('/assets/myfile.json')
      .pipe(catchError(error => of(null)))
      .subscribe(data => console.log(data))
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-27
    • 2023-03-09
    • 2015-03-02
    • 1970-01-01
    • 2020-08-09
    相关资源
    最近更新 更多