【问题标题】:Angular HttpClient data undefined out of subscribe [duplicate]Angular HttpClient数据未定义订阅[重复]
【发布时间】:2017-11-14 11:34:06
【问题描述】:

我无法使用 REST API 设置简单的 GET 查询。

出于演示目的,我使用了这个 REST 端点: https://jsonplaceholder.typicode.com/posts/1

离开 subscribe 方法的作用域时,似乎所有接收到的数据都丢失了。我遵循了多个教程,还说在不进行类型转换的情况下访问属性时会出错,但它对我来说很好。为什么会这样?

import { Injectable } from '@angular/core';
import { HttpClient  } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

import * as _ from 'lodash';    

@Injectable()
export class TestService {

    constructor(private http : HttpClient ) { }

    private URI = 'https://jsonplaceholder.typicode.com/posts/1';
    o : object;
    //Object { userId: 1, id: 1, title: "sunt aut facere repellat provident 
    //…", body: "quia et suscipit suscipit recusanda…" }

    getData(): void
    {
        this.o = this.http.get(this.URI ).subscribe();

        this.http.get<Post>(this.URI ).subscribe(response => {
            console.log(response)//shows up  
            this.o = response;
            console.log(this.o);//shows up
        } );
        console.log(this.o);//undefined
     } 
}

interface Post{
    userId: number;
    id : number;
    title : string;
    body : string;
}

Screenshot of the console

【问题讨论】:

  • 您了解您正在异步获取数据吗?
  • 这行this.o = this.http.get(this.URI ).subscribe();有什么用?
  • 此行可以删除。应该是“this.o = response;”就像在下面的订阅正文中一样。什么说明我看不懂。

标签: angular rest get undefined httpclient


【解决方案1】:

更新 1:

ngOnInit() {
  this.thingService.getThingsGoing()
  .subscribe(data => this.success(data), err => this.failed(err));
}

success(data){
  console.log(data); // <== Use it here
}

failed(err){
  console.log(err);
}

首先,你用错了。您在同一个 URL 上发出 2 个请求。

this.o = this.http.get(this.URI ).subscribe();   // <==== Request 1 / No need        
    this.http.get<Post>(this.URI ).subscribe(response => {    
        console.log(response)//shows up  
        this.o = response;
        console.log(this.o);//shows up        
    } );   // <==== Request 2
    console.log(this.o);//undefined  

您正在进行异步调用,this.o 将是 undefined,因为应用程序尚未收到数据。

当你写在subscribe()时它会在客户端收到实际数据时显示。

【讨论】:

  • 其实我也是在subscribe里写的。我正在努力解决如何从订阅之外访问接收到的数据。此外,当向方法添加返回值并在另一个组件中调用此方法时,我也会得到未定义。
  • 哦,我已经在那个场景中更新了答案
猜你喜欢
  • 2020-02-15
  • 2019-09-14
  • 1970-01-01
  • 2018-04-24
  • 2017-06-19
  • 1970-01-01
  • 2021-05-16
  • 1970-01-01
  • 2017-12-04
相关资源
最近更新 更多