2017-06-03 42 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调用所以,这个服务的数据或任何动作使用结果都应放入订阅功能中。

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

    }