Bruno Ornelas
Bruno Ornelas

Reputation: 331

Ionic2: Making a get request in a service with HttpClient gets undefined on component

When I try to make a GET request using a service I can print successfully the response inside this service (data.service.ts) but when I try to get this on a component, it gets undefined (send.component.ts)

data.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/map']

@Injectable()
export class DataService {

    getBusiness(){
        this.http.get('http://127.0.0.1/business').subscribe(data => {
            this.BUSINESS = data;
            return this.BUSINESS;
        });
    }

    constructor(private http:HttpClient){}

}   

send.component.ts

import { DataService } from '../../app/data.service';

@Component({
  selector: 'page-send',
  templateUrl: 'send.html'
})
export class SendPage {

  constructor(private dataService:DataService) {
    this.title = navParams.get('title');

    console.log(dataService.getBusiness())
  }
}

JSON response:

[{
    "_id": "5a0cf90cf3de893b000b8e3b",
    "name": "business2",
    "boxes": ["dasdsadsdasbox", "dsadajhhgbox"],
    "users": ["user2"],
    "deleted": false
}, {
    "_id": "5a0cf90cf3de893b321321",
    "name": "business1",
    "boxes": ["dasds321321box", "ds321321hgbox"],
    "users": ["user1"],
    "deleted": false
}]

Why does it happens and how to fix it?

Thank you!

Upvotes: 0

Views: 38

Answers (1)

AddWeb Solution Pvt Ltd
AddWeb Solution Pvt Ltd

Reputation: 21691

try below code :

data.service.ts

getBusiness(){
       return new Promise(resolve => {
           this.http.get('http://127.0.0.1/business')
             .subscribe(data => {
               resolve(data.json());
             });
         });
}

send.component.ts

constructor(private dataService:DataService) {
    this.title = navParams.get('title');
    dataService.getBusiness().then(res => {
       console.log('Responce =>'res);
    })
  }

Upvotes: 1

Related Questions