0

I'm trying to get json data from the url, but i'm not able to get any. It is just showing an empty array. What do you think that I'm missing here?

service.ts

this is the service.ts. Im trying to get data from 'https://jsonplaceholder.typicode.com/posts'.

import { Injectable } from '@angular/core';
import{UserCreation} from '../../models/user-creation.model';
import{Observable} from 'rxjs/Observable';
import{of} from 'rxjs/observable/of';
import{catchError,map,tap} from 'rxjs/operators';
import{HttpClient,HttpHeaders} from '@angular/common/http';

const httpOptions={
    headers:new HttpHeaders({'Content-Type':'application/json'})
};

@Injectable({
providedIn: 'root'
})

export class UserCreationService{

//Create constructor to get Http instance
constructor(private http:HttpClient) { }

private usersUrl:'https://jsonplaceholder.typicode.com/posts';

getUsers():Observable<UserCreation[]>{

return this.http.get<UserCreation[]>(this.usersUrl).pipe(
tap(receivedUsers 
=>console.log(`receivedUsers=${JSON.stringify(receivedUsers)}`)),
catchError(error=>of([]))
);
}

app.component.ts

this is the component.ts file

import { Component, OnInit } from '@angular/core';
import { Http, Response } from '@angular/http';
import { UserCreationService } from '../../common/services/user- 
creation.service';


@Component({
selector: 'app',
templateUrl: './app.component.html',
styleUrls: ['./app-component.css']
})

export class AppComponent implements OnInit {

allUsers: UserCreation[];

constructor(private userService: UserCreationService) { }

getUsersFromServices():void{
this.userService.getUsers().subscribe(
  (Users)=>{
    this.allUsers=Users;
    console.log(`this.allUsers = ${JSON.stringify(this.allUsers)}`);

  }
 )
}

ngOnInit(): void {
this.getUsersFromServices();
}
3
  • 2
    Is that API even getting called? I think private usersUrl:'https://jsonplaceholder.typicode.com/posts'; should contain = sign instead of : like this - private usersUrl='https://jsonplaceholder.typicode.com/posts'; Commented Oct 1, 2018 at 7:58
  • does console.log(receivedUsers=${JSON.stringify(receivedUsers)})), print anything Commented Oct 1, 2018 at 7:58
  • @JigneshM.Khatri well caught, you should make that an answer Commented Oct 1, 2018 at 7:59

1 Answer 1

2

There is typo error here - private usersUrl:'https://jsonplaceholder.typicode.com/posts';.

It should be = instead of : like this - private usersUrl='https://jsonplaceholder.typicode.com/posts';.

Or better way private usersUrl:string = 'https://jsonplaceholder.typicode.com/posts';

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.