【问题标题】:angular2 - cannot get data from web serviceangular2 - 无法从 Web 服务获取数据
【发布时间】:2016-12-12 00:50:49
【问题描述】:

第一次学习 typescript 和 angular2。我正在创建一个只执行 GET 和 POST 的通用服务,以便我可以在整个应用程序中使用它。我的应用程序基于来自 Dynamic Forms 的 Angular 示例

我的问题是我的“QuestionService”正在使用“ServerService”,但它抱怨this.ServerService.getData is not a function 不是一个函数。

服务器服务

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

问题服务

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

【问题讨论】:

    标签: web-services angular angular2-observables


    【解决方案1】:

    您需要做的是让 Angular 将ServerService注入QuestionService,就像在ServerService 中使用Http 一样

    @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 {}
    

    【讨论】:

      猜你喜欢
      • 2018-07-03
      • 2021-09-07
      • 1970-01-01
      • 2014-01-21
      • 1970-01-01
      • 2016-05-14
      • 2018-04-24
      • 2017-04-11
      • 1970-01-01
      相关资源
      最近更新 更多