0

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

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

Screenshot of the console

Sangwin Gawande
  • 7,658
  • 8
  • 48
  • 66
Plagueis
  • 173
  • 1
  • 3
  • 12

1 Answers1

1

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

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  

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

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

Sangwin Gawande
  • 7,658
  • 8
  • 48
  • 66
  • 1
    Actually I wrote it in subscribe as well. I'm struggling with how to access the received data outside from subscribe. Also when add return value to the method and call this method in another component I also get undefined. – Plagueis Nov 14 '17 at 12:21
  • Oh, I have updated Answer in that scenario – Sangwin Gawande Nov 14 '17 at 12:32