2017-12-07 14 views
0

サービスを使用してGETリクエストを作成しようとすると、このサービス(data.service.ts)の応答は正常に印刷できますが、コンポーネント、それは未定義ます(send.component.tsIonic2:コンポーネントでHttpClientを使用したget要求を定義しません。

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 
}] 

は、なぜそれが起こるんし、それを修正する方法?

ありがとうございました!コードの下

+0

HTTPリクエストから値を返す[Ionic2の可能性のある重複変数に代入する](https://stackoverflow.com/questions/43337354/ionic2-returning-a-value-from-http-request-and-ass)変数にign-it-to-variable) –

答えて

1

試してみてください。

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

エラーを表示します。 Typescriptエラー 'subscribe'プロパティが 'void'型に存在しません。 –

+0

私の更新の回答 –

+0

を確認してください。 "res.jsonは関数ではありません"というエラーが表示されます。リクエストを返すべきjsonで質問を更新しました。 –

関連する問題