0

I've looked at various webpages, including this stack overflow question: How to get data from observable in angular2

All of the information says that I need to subscribe to the Observable and then do something with the data within the next function, which is exactly what I'm doing. But what gets logged to the console isn't the body of the request, it seems to be something else that looks like this.

Response {type: "cors", url: "https://reqres.in/api/users?page=1", redirected: false, status: 200, ok: true, …}
body: ReadableStream
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: ""
type: "cors"
url: "https://reqres.in/api/users?page=1"
__proto__: Response

I can get the body of the Observable by using body() but this just returns a ReadableStream object and not the JSON string I'm expecting?

Here is my code.

 const data = from(fetch('https://reqres.in/api/users?page=1'));

    data.subscribe({
      next(response) {
        console.log(response);
        },
      error(err) { console.error('Error: ' + err); },
      complete() { console.log('Completed'); }
    });

What do I need to do to get the JSON string that is found at the endpoint specified so I can actually do something with it. Do I need to map the stream to an object or something?

Jake12342134
  • 1,539
  • 1
  • 18
  • 45

3 Answers3

2

I'm just not sure why you're using from here. I'm assuming that all you need here is to hit the API url and get the data from it.

If that's actually the case, you can simply use the get method on HttpClient which you'll have to inject as a dependency in your Component.

Also, to use HttpClient, you'll have to add HttpClientModule to the imports array of your module.

If you're actually following this, your code can then be transformed like:

constructor(private http: HttpClient ) {}

....

getData() {
  this.http.get('https://reqres.in/api/users?page=1').subscribe(
    response => console.log(response),
    err => console.error('Error: ' + err),
    () => console.log('Completed')
  );
}

If you still want to use from and fetch, then you'll have to do what m1gu3l has suggested.

const data = from(fetch('https://reqres.in/api/users?page=1').then(res => res.json()))
  .subscribe(
    response => console.log(response),
    err => console.error('Error: ' + err),
    () => console.log('Completed')
  );

But then this is something that Http used to do during the time of Angular 4.3 and prior versions of Angular but was eventually deprecated in favor of HttpClient where you don't really need to call the json method to get the exact response data.


Here's a Working Sample StackBlitz for your ref.

SiddAjmera
  • 38,129
  • 5
  • 72
  • 110
  • The use of `from` is because I was attempting to copy what this website is describing: https://angular.io/guide/rx-library – Jake12342134 Jul 02 '19 at 12:05
  • @Jake12342134, I've also updated a working sample stackblitz that might help :) – SiddAjmera Jul 02 '19 at 12:10
  • It did, thanks! One small question though. I have the response object now, and I want to get the `data` array within the response that holds the user data, I've tried to do `response[data]` but that gives an error, what do I need to do to access it? – Jake12342134 Jul 02 '19 at 12:26
0

fetch is returning a Promise with Response. You can use json() method.

const data = from(
    fetch('https://reqres.in/api/users?page=1')
        .then(r => r.json())
);

m1gu3l
  • 763
  • 1
  • 6
  • 19
  • This doesn't work, the promise is still wrapped in an Observable so all I get if I do `Console.log(response.json())` is `Promise {} __proto__: Promise [[PromiseStatus]]: "resolved" [[PromiseValue]]: Object` – Jake12342134 Jul 02 '19 at 12:02
  • This may depend on rxjs version, but for some time from unwraps Promises https://codesandbox.io/s/dazzling-euclid-mubku – m1gu3l Jul 02 '19 at 12:45
0

If you use fetch() instead of Angular's HTTPClient, you have to transform it to JSON -

const data = from(fetch('https://reqres.in/api/users?page=1'));

data.map(res => res.json()).subscribe(json =>{
  console.log(json);
});
Uday Vunnam
  • 337
  • 2
  • 5