Angular 角度rxjs:如果http.get可以';找不到json文件
在我的Angular应用程序中;我习惯于从静态json文件获取数据 像这样:Angular 角度rxjs:如果http.get可以';找不到json文件,angular,typescript,ecmascript-6,rxjs,Angular,Typescript,Ecmascript 6,Rxjs,在我的Angular应用程序中;我习惯于从静态json文件获取数据 像这样: @Injectable() export class ConfigService { constructor(private http: HttpClient) { } getData() { this.http.get('/assets/myfile.json').subscribe(data => { console.log(data); }) } } 在某
@Injectable()
export class ConfigService {
constructor(private http: HttpClient) { }
getData() {
this.http.get('/assets/myfile.json').subscribe(data => {
console.log(data);
})
}
}
在某些脚本中,myfile.json
可能不存在
(这是出于其他目的而需要的)
在这种情况下,我不想得到这个错误:
HttpErrorResponse:解析的过程中Http失败
但很简单,我想得到一个null
响应
建议???如评论中所述,您可以这样使用运算符:
getData() {
this.http.get('/assets/myfile.json')
.pipe(catchError(error => of(null)))
.subscribe(data => console.log(data))
}
您可以使用catchError()
和返回of(null)
或根据某些条件重新显示错误。