【问题标题】:Get contents of json file not working获取json文件的内容不起作用
【发布时间】:2017-01-18 20:02:41
【问题描述】:

我想使用 angular 2 http.get 从 json 文件中获取 json 对象。我最终从文件中得到的是:

t_isScalar: falseoperator: tsource: t__proto__: Object

这是我的代码

@Injectable()
export class ValidateJSONSchemaService {

    constructor(private http: Http) { }

    getSchema(fileName): any {
        return(this.http.get(fileName)
            .map(this.extractData)
        );
    }

    private extractData(res: Response) {
        let body = res.json();
        return body.data || {};
    }
}

如何修复 getSchema 以使其返回 json 对象而不是这个:t_isScalar: falseoperator: tsource: t__proto__: Object。请注意,当我更改文件名时,它会返回相同的内容。我本来预计会出现信息性错误(我确实进行了错误处理,但代码从未出错)。

【问题讨论】:

    标签: json angular angular2-http


    【解决方案1】:

    你需要subscribe才能观察到:

    @Injectable()
    export class ValidateJSONSchemaService {
    
        constructor(private http: Http) { }
    
        getSchema(fileName): any {
            return(this.http.get(fileName)
                .map(this.extractData).subscribe(data => console.log(data));
            );
        }
    
        private extractData(res: Response) {
            let body = res.json();
            return body.data || {};
        }
    }
    

    【讨论】:

      【解决方案2】:

      除了 Maciej 的回答之外,您还可以使用 | async 管道为您进行订阅。

      <div>{{getSchmea('fileName') | async}}</div>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-24
        • 2013-04-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多