-4

I am working with Angular and WordPress rest API. Everything is going fine. But I have a little confusion with the behavior of the following code.

getpost(){
    return this.http.get('someURL');
}

The above function is residing in a service. When I try to subscribe to the returned observable, I get an error. But the code below is working fine.

getpost(){
    let someVAR = this.http.get('someURL');
    return someVAR;
} 

Please clarify WHY the above code is not returning observable. thanks in advance

jai lani
  • 9
  • 3

3 Answers3

2

You can try something like this.

class PostService {
   public getpost(userId): Observable<any> {
        return this.http.get<any>(this.apiurl + 'user/posts/' + userId);
      }
}

class MyClass implements OnInit {
      post: any;

      constructor(private myService: MyService) {
        this.userInformation = JSON.parse(localStorage.getItem('user'));
      }

      ngOnInit() {
        this.myService.getpost(userId).subscribe((posts) => {
          this.post = post;
        })
      }
   }
Divyanshu Rawat
  • 4,421
  • 2
  • 37
  • 53
0

The code you're showing here will work. But in order to make the http call, you need to subscribe to that observable.

public getData() {
return this.http.get('someUrl');
}

export class MyComponent { 

constructor(private myService: MyService){}
usingData() {
this.myService.getData().subscribe(data => { // do stuff with the data  })
}

I'm not sure how you're currently using it but the above is how it should work.

SebastianG
  • 8,563
  • 8
  • 47
  • 111
  • Thanks Michael. Actually the function getData() resides in a service. And I need to subscribe to the observable from a component. I just want to know why the first line of my code is not returning the observable – jai lani Sep 19 '19 at 16:13
  • @jailani it's supposed to work, you've got a bug somewhere that you're not seeing but that is the corect usage. I have updated my post with an example from a srevice – SebastianG Sep 20 '19 at 08:47
0

Well here are some steps how to call http request using HttpClient:

HttpClient using import { HttpClient } from '@angular/common/http';

and then you need to subcribe the observable (also you can use RxJS to do more with the observable).

constructor(
    private httpClient: HttpClient
) { }

ngOnInit() { 
    // 2. Then you need to subscribe the observable
    this.getPost().subscribe(resp => {
       console.log("When success", resp);
    }, err => {
       console.log("When error", err);
    });
}

getPost() {
    return this.httpClient.get('someURL'); // 1. This will return the observable
}
Snowbases
  • 2,316
  • 2
  • 20
  • 26