2017-06-03 3 views
0

RESTサービスを呼び出そうとしていますが、このようなことをやっています。すべてのHTTP要求に ベースクラス:Angular 2の継承を使用してリクエストを要求

import { Injector } from '@angular/core'; 
    import 'rxjs/add/operator/map'; 
    import { Http, Response, Headers, RequestOptions } from '@angular/http'; 
    import {Observable} from 'rxjs/Rx'; 
    export class HttpRoot { 
     public url:string; 
     public type:string; 
     protected http:Http; 
     constructor(public injector:Injector){ 
     this.http = injector.get(Http); 
     }; 
     callAPI(){ 
     return this.http.get(this.url).map((resCont:Response) => { 
      console.log(resCont); 
      return resCont; 
     }).catch((error:any) => Observable.throw(error.json().error || 'Server error')); 
     } 
     successHandler(res:any){ 
     console.log('there'); 
     } 
     failureHandler(res:any){ 

     } 
    } 

子クラス拡張HttpRoot

import { HttpRoot } from './HttpRoot'; 
import { Injector } from '@angular/core'; 
import { Http, Response, Headers, RequestOptions } from '@angular/http'; 
export class HttpGet extends HttpRoot { 
    constructor(public injector:Injector,public url:string){ 
    super(injector); 
    this.type="GET"; 
    }; 
} 

そして最後に、私は、このサービスに私のコンポーネントには、このサービスを注入して呼び出しています

import { Injectable,Injector } from '@angular/core'; 
import { Http, Response, Headers, RequestOptions } from '@angular/http'; 
import { HttpGet } from './API/HttpGet'; 
import {Observable} from 'rxjs/Rx'; 
@Injectable() 
export class CommentsService { 

    commentsUrl:string="../data/data.json"; 
    constructor(private http:Http,private injector:Injector){ 

    }; 
    comments:any[]; 
    private getRequest:HttpGet; 
    // 
    getComments(){ 
    this.getRequest=new HttpGet(this.injector,this.commentsUrl); 
    var returnRES = this.getRequest.callAPI(); 

    } 
} 

にサービスを提供getCommnetsメソッドを使用しています。ブレークポイントを使用すると、HttpRootのcallAPIが呼び出されていますが、配置しているAjaxリクエストはありません。 誰かが私が間違っているところで助けてもらえますか?

答えて

1

私たちが購読するとHTTPサービスがリクエストします。 これはajaxコールなので、このサービスのデータやアクションの使用結果をsubscribe関数内に入れる必要があります。

getComments(){ 
    this.getRequest=new HttpGet(this.injector,this.commentsUrl); 
    this.getRequest.callAPI().subscribe(data => { 
     var returnRES = data; 
    }); 

    } 
関連する問題