javascript - 如何在 Angular 2/4 中返回来自响应而不是订阅 json 的数据

标签 javascript php angular

我的服务:

fetchData(url,request)
  {
    return this.http.post(this.apiUrl+url,request).subscribe(
        (response) => {return response.json()}
    );
  }

我的组件:

ngOnInit()
    {
        this.response = this.dataService.fetchData('friends/grow_network',{});
        console.log('s ',this.response);
    }

如果我在服务中控制 response.json() 它会显示来自 api 的正确数据,但如果我在组件中控制它会显示如下:

Subscriber {closed: false, _parent: null, _parents: null, _subscriptions: Array(1), syncErrorValue: null…}

如何在组件中获取来自 api 而不是订阅者数据的数据?

最佳答案

按照您的方式进行时,您在变量“响应”中写入可观察对象而不是结果。调用方法时还没有结果值,因为它将是异步的。

要获得你想要的,你必须执行以下操作:

fetchData(url,request)
  {
    return this.http.post(this.apiUrl+url,request).map(
        (response) => {return response.json()}
    );
  }

ngOnInit()
    {
        this.response = this.dataService.fetchData('friends/grow_network',{})
                         .subscribe(result => {
                           this.response = result;
                           console.log('s ',this.response);
                         });

    }

关于javascript - 如何在 Angular 2/4 中返回来自响应而不是订阅 json 的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45343140/

相关文章:

javascript - 将空元素插入 javascript 数组

当 html 在 JSON 数据包中传递时,Javascript 错误

php - 你用的哪个php变量调试功能? var_dump、print_r、var_export、其他?

php - json_encode 在 while 循环内不起作用

javascript - 页面重定向(PHP,HTML)

javascript - clearText 函数中的 'e' 参数是什么意思?

javascript - 我已经构建了自动完成输入框(但是foucsout有问题)

angular - 使用 Ajax 数据表的 Angular 服务在组件之间共享数据

具有嵌套状态的 Angular2 路由

angular - 为什么 RouterLink 将输入添加到当前 URL 末尾的括号中