0
votes

I try to get webservice via angular2 observable, but I have error

ERROR TypeError: Cannot read property 'get' of undefined

Firs I imported HttpModule in app.module.ts. I have providers for currencyService. Next I createed currency.ts (interface) Next I modyficated my 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());
    };

}

In the end 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
            )
    }
}

This is my first try to use observable, and I'm quite new in Angular2. I based on some tutoria, watch on yt several and read too, but I even don't know where could be the mistake.

1
You're missing Curly Braces after the constructor in your service - Chau Tran
Thank you very much, yep, I was my stupid mistake. I had some mistake in the same file in map part too - Eva

1 Answers

0
votes

Firstly please add curly braces and remove semicolon from your constructor.

Now, use HttpClient instead of Http (Assuming you are on Angular 5)

In your appModule:

 import {HttpClientModule} from '@angular/common/http';

In your Currency Service

import {HttpClient} from '@angular/common/http';

constructor(private _http: HttpClient){}