简体   繁体   English

Angular2:无法返回从Http响应映射的json

[英]Angular2: unable to return a json mapped from an Http response

In my service I execute an http call and return the response as Observable 在我的服务中,我执行http调用,并将响应返回为Observable

doQuery ( query: String ) : Observable<any> {
    return this.http.request(queryURL) ;   
}

And in a component I subscribe 在组件中,我订阅

this.service
    .doQuery(this.query)
    .subscribe((res: any) => {
        console.log ("Res");
        console.log(res);
    });

Doing this actually works; 这样做确实有效; I can see in the console the dump of a Response object 我可以在控制台中看到Response对象的转储

My problem came when I want to return from the service the response alread mapped as json. 当我想从服务中返回已经映射为json的响应时,我的问题就来了。

I trying to do tyhis 我试图做tyhis

return this.http.request(queryURL).map((res: any) => res.json());

But at runtime I got an obscure javascript error (this is coming from Zone.js to be precise) 但是在运行时,我遇到了一个晦涩的javascript错误(确切地说,这是来自Zone.js的错误)

Error: Permission denied to access property "rejection"

I've already tried to change the return type from Observable<any> to Observable<any[]> , as seen on a book, but without success. 我已经尝试将返回类型从Observable<any>更改为Observable<any[]> ,就像在书上看到的那样,但是没有成功。

UPDATE : Actually I resolved adding into the service file this import 'rxjs/Rx'; 更新 :实际上我解决了将import 'rxjs/Rx';添加到服务文件中import 'rxjs/Rx';

What am I doing wrong? 我究竟做错了什么? Why is this import needed ? 为什么需要此导入? Isn't a way to import Rxjs' map operator? 导入Rxjs的地图运算符不是一种方法吗?

In this specific situation, i resolved adding the import 在这种特定情况下,我决定添加导入

import `rxjs/Rx`;

But in the 99% of other times this happened again to me, this error was due to a missing declaration of one service in the providers array in the @NgModule 但是在其他99%的情况下,这种情况再次发生在我身上,此错误是由于@NgModule的providers数组中缺少一项服务的声明引起的

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

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