在我的angular 2项目中使用ng2智能表,我需要使用http.post()方法发送API请求,我创建了一个服务并注入我的组件并通过发送一个API服务调用post方法输入URL,我在我的控制台中得到以下异常
EXCEPTION:Uncaught(在promise中):TypeError:无法读取属性 '后'未定义的
我的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 :(得分: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);
}