【发布时间】:2017-11-30 13:51:04
【问题描述】:
我尝试通过 angular2 observable 获取 web 服务,但出现错误
ERROR TypeError: Cannot read property 'get' of undefined
首先我在 app.module.ts 中导入了 HttpModule。我有货币服务提供商。 接下来我创建了currency.ts(接口) 接下来我修改了我的 currency.service.ts:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { ICurrency } from './currency';
@Injectable()
export class CurrencyService {
currency:Array<ICurrency>;
constructor(private _http: Http);
getCurrency(): Observable<ICurrency[]>{
return this._http
.get('https://api.fixer.io/latest?base=PLN&symbols=EUR,USD,GBP,CZK,CHF,RUB')
.map(res: Response => <ICurrency[]>res.json());
};
}
到底是currency.component.ts:
import { Component, OnInit } from '@angular/core';
import { ICurrency } from './currency';
import { CurrencyService } from './currency.service';
@Component({
selector: 'app-currency',
templateUrl: './template.html',
styles: []
})
export class CurrencyComponent implements OnInit {
currency: array<ICurrency>;
error: string;
constructor(private _currencyService: CurrencyService) { }
ngOnInit(){
this.getCurrency();
}
getCurrency(){
this._currencyService
.getCurrency()
.subscribe(
currency => this.currency = currency,
err => this.error = <any>error
)
}
}
这是我第一次尝试使用 observable,我对 Angular2 还是很陌生。我根据一些教程,看了几本,也看了,但我什至不知道可能是哪里错了。
【问题讨论】:
-
服务中的构造函数后缺少大括号
-
非常感谢,是的,我犯了愚蠢的错误。我在地图部分的同一个文件中也有一些错误
标签: angular web-services http get observable