订阅中未定义Angular HttpClient数据

时间:2017-11-14 11:34:07

标签: angular rest get undefined httpclient

我在使用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

1 个答案:

答案 0 :(得分: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);
}

首先,你错了。您在同一个网址上发出了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()中写入时,当客户端收到实际数据时,它会显示出来。