当我在解析的JSON对象上调用map()函数时(在mapStocks()函数中如下所示),如果我将toStock()函数放在StockService类中,它就会失败。但是,如果我将该函数声明为StockService类之外的“全局”函数,则不会抛出错误。
import { Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
//import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import { Stock } from './stock';
@Injectable()
export class StockService {
private baseUrl: string = 'https://www.vendor-api-website.com';
constructor(private http: Http) {
}
getStocks(): Promise<Stock[]> {
console.log('Loading stocks...');
let stocks$ = this.http
.get(`${this.baseUrl}/api/getInventory`, { headers: this.getHeaders() })
.map(this.mapStocks)
.toPromise()
.catch(this.handleError);
return stocks$;
}
private getHeaders() {
let headers = new Headers();
headers.append('Accept', 'application/json');
return headers;
}
private handleError(error: any): Promise<any> {
//console.error('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
private mapStocks(response:Response): Stock[] {
console.log('Mapping inventory...');
// this fails...
return response.json().map(this.toStock);
// ..but this is okay?
//return response.json() as Stock[];
}
// This succeeds if declared as a function and placed outside the class
private toStock(stockObject:any): Stock {
console.log('toStock called');
let stock = <Stock>({
id: stockObject.id,
code: stockObject.code,
name: stockObject.name,
description: stockObject.description,
supplier: stockObject.supplier,
cost: stockObject.unitPrice * stockObject.minQuantity,
quantity: stockObject.minQuantity
});
console.log('Parsed stock:', stock);
return stock;
}
}
如您所见,我们需要toStock()函数,以便在将其分配给我们自己的Stock对象数组之前进行一些计算。
如果我在StockService类中声明toStock()函数,则引发的错误是: 有人可以解释为什么会这样吗?这是TypeScript的限制吗?
答案 0 :(得分:4)
您正在此处设置常规JavaScript功能:.map(this.mapStocks)
。
this
对象将更改为函数而不是类。这里this.toStock()
未定义。
使用Function.Prototype.bind()
.map(this.mapStocks.bind(this))
完成电话:
let stocks$ = this.http
.get(`${this.baseUrl}/api/getInventory`, { headers: this.getHeaders() })
.map(this.mapStocks.bind(this))
.toPromise()
.catch(this.handleError);
答案 1 :(得分:-2)
getStocks(): Promise<Stock[]> {
console.log('Loading stocks...');
let stocks$ = this.http
.get(`${this.baseUrl}/api/getInventory`, { headers: this.getHeaders() })
.map(res => { return this.toStock(res.json()) })
.catch(this.handleError);
}