2016-12-12 17 views
0

初めてタイプ2を入力してください。& angular2私はGETとPOSTを行う汎用サービスを作成していますので、アプリ全体で使用できるようになりました。私のアプリはAngularの例に基づいていますDynamic Formsangular2 - Webサービスからデータを取得できません。

私の "QuestionService"は "ServerService"を使用していますが、this.ServerService.getData is not a functionが機能していないと不満を言っています。

ServerService

import { Injectable }  from '@angular/core'; 
import { Http, Response } from '@angular/http'; 

import { Observable }  from 'rxjs/Observable'; 

@Injectable() 
export class ServerService { 

    private apiUrl = 'app/users.json'; 

    constructor (private http: Http) {} 

    getData(): Observable<any>[] { 
    return this.http.get(this.apiUrl) 
        .map(this.extractData) 
        .catch(this.handleError); 
    } 

QuestionServiceここ

import { ServerService } from './server.service'; 

@Injectable() 
export class QuestionService implements OnInit{ 

    errorMessage: string; 
    mode = 'Observable'; 
    questions: QuestionBase<any>[]; 
    ServerService = ServerService; 

    ngOnInit() { this.getQuestions(); } 

    getQuestions(ServerService: ServerService<any>){ 
     console.log('getQuestions'); 
     console.log(this.ServerService.getData()); 

     this.ServerService.getData() 
        .subscribe(
         questions => this.questions = questions, 
         error => this.errorMessage = <any>error); 
    } 

は、URLである:あなたがする必要がどのようなhttps://plnkr.co/edit/InWESfa6PPVKE0rXcSFG?p=preview

答えて

0

は角度ServerServiceを注入させていますQuestionServiceに、ちょうどその時あなたはproviders配列

@NgModule({ 
    imports: [HttpModule], 
    providers: [ServerService, QuestionService] 
}) 
export class AppModule {} 
に両方のサービスを追加する必要があり ServerService

@Injectable() 
export class QuestionService implements OnInit{ 

    constructor(private serverService: ServerService) {} 

    ngOnInit() { this.getQuestions(); } 

    getQuestions(){ 
     this.serverService.getData() 
        .subscribe(
         questions => this.questions = questions, 
         error => this.errorMessage = <any>error); 
    } 
} 

Httpでやっているのが好き

関連する問題