angular 请求本地json数据

栏目: 编程语言 · AngularJS · 发布时间: 6年前

内容简介:本周写一个前台模块时,发现需要的数据依赖其他模块的支持,但其他模块暂时还不能用,所以需要手动添加模拟数据,然后参考模板demo,发现很有意思的写法,于是就拿来借鉴了。在assets/demo/data目录下创建checkRecord.json文件,如图添加数据:

本周写一个前台模块时,发现需要的数据依赖其他模块的支持,但其他模块暂时还不能用,所以需要手动添加模拟数据,然后参考模板demo,发现很有意思的写法,于是就拿来借鉴了。

1. 添加json测试数据

在assets/demo/data目录下创建checkRecord.json文件,如图添加数据:

angular 请求本地json数据

2. 请求数据

在check-record.service.ts文件中

getAll(): Observable<CheckRecord[]> {
   return this.http.get<CheckRecord[]>('assets/demo/data/checkRecord.json');
}

在check-record.component.ts文件中:

// 获取检定记录
getAllCheckRecords(): void {
    this.checkRecordService.getAll().subscribe((checkRecords: CheckRecord[]) => {
        this.checkRecords = checkRecords;
        console.log(checkRecords);
    }, () => {
        console.log('network error');
    });
}

结果发现写完后,控制台报404

angular 请求本地json数据

发现请求路径上多了'api',于是就去改拦截器

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // 如果请求的是本地资源,则不进行拦截
    if (req.url.slice(0, 6) !== 'assets') {
        const apiReq = req.clone({
            url: '/api' + req.url
        });
        return next.handle(apiReq);
    } else {
        return next.handle(req);
    }
}

再次请求,请求数据成功:

angular 请求本地json数据

总结

发现平时开发还是太依赖前后台相互配合,不能做到完全的前后台分离开发,这次参考别人的写法,学到了一手。


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Distributed Systems

Distributed Systems

Sukumar Ghosh / Chapman and Hall/CRC / 2014-7-14 / USD 119.95

Distributed Systems: An Algorithmic Approach, Second Edition provides a balanced and straightforward treatment of the underlying theory and practical applications of distributed computing. As in the p......一起来看看 《Distributed Systems》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换