Ionic2:在使用HTTPCLIENT的服务中提出get请求在组件上不确定



当我尝试使用服务做出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);
    })
  }

相关内容

  • 没有找到相关文章

最新更新