Angular HttpClient数据未定义出订阅 [英] Angular HttpClient data undefined out of subscribe

查看:118
本文介绍了Angular HttpClient数据未定义出订阅的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm having trouble with setting up simple GET query with a REST API.

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

For demonstration purposes I used this REST endpoint: https://jsonplaceholder.typicode.com/posts/1

当离开订阅方法的范围时,似乎所有接收到的数据都会丢失.我遵循了多个教程,也说在不进行类型转换的情况下访问属性时会出现错误,但对我来说很好.为什么会这样?

It seems that all received data is lost when leaving the scope of the subscribe method. I followed multiple tutorials, that also said I would get a error when accessing attributes without typecasting, but it works fine for me. Why is that so?

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;
}

控制台的屏幕截图

推荐答案

更新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个请求.


First of all, You are using it wrong. You are making 2 requests on the same URL.

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.

You are making async call, this.o will be undefined because application has not received the data yet.

当您在subscribe()中编写它时,它将在客户端收到实际数据时显示.

When you write it in subscribe() it will be showed up when client receives actual data.

这篇关于Angular HttpClient数据未定义出订阅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆