簡體   English   中英

Ionic2:使用HttpClient在服務中發出get請求在組件上未定義

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

當我嘗試使用服務發出GET請求時,我可以在該服務( data.service.ts )中成功打印響應,但是當我嘗試在組件上獲取該響應時,該響應將變得不確定( 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響應:

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

為什么會發生以及如何解決?

謝謝!

試試下面的代碼:

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);
    })
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM