2016-12-15 5 views
0

Я использую смарт-таблицу ng2 в своем проекте с угловым 2, мне нужно отправить запрос API с использованием метода http.post(), я создал Сервис и ввел его в свой компонент и вызвал после метод из службы API, отправив ввод с URL, я получаю следующее исключение в моей консолиng2 smart table api request post метод не работает

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); 
    } 
Смежные вопросы