2016-12-15 68 views
0

我在我的angular 2項目中使用ng2智能表,我需要使用http.post()方法發送一個API請求,我創建了一個Service並注入到我的組件中並調用通過發送帶有URL輸入API服務方法後,我收到以下異常在我的控制檯ng2智能表api請求發佈方法不工作

EXCEPTION: Uncaught (in promise): TypeError: Cannot read property 'post' of undefined

我APIService

import { Injectable } from '@angular/core'; 
import { Http, Headers, Response } from '@angular/http'; 
import { Observable } from 'rxjs'; 
import 'rxjs/add/operator/map' 

@Injectable() 
export class ApiService { 
    public token: string; 
    private endpoint: string = 'MYENDPOINT'; 
    constructor(private http: Http) {} 

    private process(response:Response) { 
     let json = response.json(); 
     if (json && json.errorMessage) { 
      throw new Error(json.errorMessage); 
     } 
     return json; 
    } 

    private processError(error: any) { 
     let 
      errMsg = (error.message) ? error.message : error.status ? `${error.status} - ${error.statusText}` : 'Server error'; 
     console.error(errMsg); // log to console instead 
     return Observable.throw(errMsg); 
    } 


    getHeaders() { 
     let headers = new Headers(); 
     headers.append('Content-Type', 'application/json'); 
     if(this.token) { 
      headers.append('Authorization', this.token); 
     } 
     return { 
      headers: headers 
     }; 
    } 

    get(url) { 
     return this 
      .http 
      .get(this.endpoint + url, this.getHeaders()) 
      .toPromise() 
      .then(this.process) 
      .catch(this.processError); 
    } 

    post(url, data) { 
     return this 
      .http 
      .post(this.endpoint+ url, data, this.getHeaders()) 
      .toPromise() 
      .then(this.process); 
    } 

    put(url, data) { 
     return this 
      .http 
      .put(this.endpoint+ url, data, this.getHeaders()) 
      .toPromise() 
      .then(this.process) 
      .catch(this.processError); 
    } 

    apiURL(magazine) { 
     return this.endpoint 
    } 

    delete(url) { 
     return this 
      .http 
      .delete(this.endpoint+ url, this.getHeaders()) 
      .toPromise() 
      .then(this.process) 
      .catch(this.processError); 
    } 

    setToken(token) { 
     localStorage.setItem('ssid', token); 
     this.token = token; 
    } 

} 

app.Component

import {Component, ViewEncapsulation} from '@angular/core'; 
import {Router} from '@angular/router'; 
import { LocalDataSource } from 'ng2-smart-table'; 
import {ApiService} from './apiService' 
import { Http } from '@angular/http/src/http'; 
@Component({ 
    selector: 'buttons', 
    encapsulation: ViewEncapsulation.None, 
    styles: [require('./buttons.scss')], 
    template: require('./buttons.html'), 
}) 

export class Buttons extends LocalDataSource{ 
    busy: Promise<any>; 
settings = { 
    columns: { 
     UNIQUE_ID: { 
     title: 'Unique ID' 
     }, 
     NAME: { 
     title: 'Name' 
     }, 
     DOB: { 
     title: 'Date of Birth' 
     }, 
     LOAN_AMOUNT: { 
     title: 'Loan Amount' 
     }, 
     STATUS:{ 
     title :'Status' 
     } 
    } 
    }; 
    constructor(private api:ApiService,private _router:Router) { 
    super(null); 
    } 


    getElements(): Promise<any> { 
    debugger 
    let inpReq= JSON.stringify({"vendorID": 1}) 
    this.busy = new Promise(resolve => {}); 
    return this.api 
     .post('http://apiservice:80/api/GetReviewList',inpReq) 
     .then(data => this.data = data); 
    } 

    public LoadReviewScreen(){ 
this._router.navigate(['pages/reviewscreen']); 
    } 
} 

請幫我解決這個問題

回答

0
import { Injectable } from '@angular/core'; 
import { Http, Response, Headers, `RequestOptions`} from '@angular/http'; 
import 'rxjs/Rx'; 
import { Observable }  from 'rxjs/Observable'; 
import 'rxjs/add/operator/map'; 

please follow this pattern in you api and then try it again. because you are missing some file to import 


    public Post(data: any, url: string): Observable<any> { 

    let body = JSON.stringify(data); 
    let headers = new Headers({ 'Content-Type': 'application/json' }); 
    let options = new RequestOptions({ headers: headers }); 

    return this._http.post(this.URL + url, body, options) 
     .map(res => res.json()) 
     .catch(this.handleError); 

    } 


private handleError (error: Response | any) { 
    // In a real world app, we might use a remote logging infrastructure 
    console.error('web api error 1'); 
    console.error(error); 
    let errMsg: string; 
    if (error instanceof Response) { 
     const body = error.json() || ''; 
     const err = body.error || JSON.stringify(body); 
     errMsg = `${error.status} - ${error.statusText || ''} ${err}`; 
    } else { 
     errMsg = error.message ? error.message : error.toString(); 
    } 
    console.error('web api error 2'); 
    console.error(errMsg); 
    return Observable.throw(errMsg); 
    }