angular2 - 无法从Web服务获取数据

时间:2016-12-12 00:50:50

标签: web-services angular angular2-observables

学习打字稿& angular2第一次。我正在创建一个只执行GET和POST的通用服务,以便我可以在整个应用程序中使用它。我已根据Dynamic Forms

中的Angular示例创建了我的应用程序

我的问题是我的问题服务"正在使用" ServerService"但它抱怨this.ServerService.getData is not a function不是一个功能。

Server服务

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

以下是网址:https://plnkr.co/edit/InWESfa6PPVKE0rXcSFG?p=preview

1 个答案:

答案 0 :(得分:0)

您需要做的是让Angular ServerService注入<{1}}到QuestionService,就像在Http中使用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);
    }
}

然后您需要将两个服务添加到providers数组

@NgModule({
  imports: [HttpModule],
  providers: [ServerService, QuestionService]
})
export class AppModule {}