我尝试通过angular2 observable获取webservice,但我有错误
错误TypeError:无法读取未定义的属性'get'
我在app.module.ts中导入了HttpModule。我有currencyService的提供者。 接下来我创建了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中很新。我基于一些tutoria,观看几个并阅读,但我甚至不知道哪里可能是错误。
答案 0 :(得分:0)
首先请添加花括号并从构造函数中删除分号。
现在,使用HttpClient而不是Http(假设你在Angular 5上)
在您的appModule中
import {HttpClientModule} from '@angular/common/http';
在您的货币服务中
从'@ angular / common / http'导入{HttpClient};
constructor(private _http: HttpClient){}