Search code examples
angularangular-services

Angular - Fetch data using angular service


I am trying to fetch details. So, here is my code.

data.service.ts

 import { Injectable } from '@angular/core';
 import { Http, Headers } from '@angular/http';
 import 'rxjs/add/operator/map';
 import { HttpClient,HttpErrorResponse } from 
 '@angular/common/http';
 import { ActivatedRoute, Router } from '@angular/router';


 export class DataService {

 constructor(private http: HttpClient) {}

 userdetails() {
  return this.http.get(`http://jsonplaceholder.typicode.com/users`);
  }

}

home.component.ts

  import { Component, OnInit } from '@angular/core';
  import { DataService } from '../data.service';
  import { ActivatedRoute, Router } from '@angular/router';
  import { HttpClient } from '@angular/common/http';
  import { userInfo } from 'os';
  @Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
  })
  export class HomeComponent implements OnInit {
  user:any

  constructor(private data: DataService) { }

  ngOnInit()
   {
     this.data.userdetails().subscribe(
      allData => {
      this.user = allData;
      return this.user;
   });

   }
   }

home.component.html

 <div *ngFor="let x of allData">
   {{{x.name}}
 </div>
 <router-outlet></router-outlet>

I am getting some syntax error in home.component.ts and other error like "Can't resolve all parameters for DataService: (?)." . Please help me guys.


Solution

  • You can try code below or seen: API IN ANGULAR 7

    File servive when request API, you need add
        const httpOptions = {
          headers:new HttpHeaders({'Content-Type':'application/json'})
        };
    
        /*
        * METHOD POST
        */
        sendpost(value: any) {
            return this.http.post<any>('http://jsonplaceholder.typicode.com/posts', value,httpOptions)
                .pipe(map(user => {
                    return user;
                }));
        }
    
        /**
         * METHOD GET
         */
        getdetails(){
            return this.http.get<any>('http://jsonplaceholder.typicode.com/users')
                .pipe(map(item => {
                    return item;
                }));
        }
    
     ------------------------------------------------------------------------------------------------ 
    File HomeComponent.ts: you import file serivice
    import {UserService} from '../_services/user.services'
    dataItem:any = {} 
     constructor(private _userService:UserService){
           this._userService.getdetails().subscribe(item=>{
                console.log(item);
                this.dataItem=item;
            })
     }
     
     
    ------------------------------------------
    show HomeComponent.html
    
    <ul *ngIf="dataItem?.length>0">
        <li *ngFor='let item of dataItem'>
            {{item.name}} - {{item.username}}
        </li>
    </ul>