【问题标题】:Angular2 get observable ERROR TypeError: Cannot read property 'get' of undefinedAngular2 获得可观察到的错误类型错误:无法读取未定义的属性“获取”
【发布时间】: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


【解决方案1】:

首先请在构造函数中添加花括号并删除分号。

现在,使用 HttpClient 代替 Http(假设您使用的是 Angular 5)

在您的 appModule 中:

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

在您的货币服务中

从“@angular/common/http”导入 {HttpClient};

constructor(private _http: HttpClient){}

【讨论】:

  • OP 说他们在 Angular 2 上
  • 这就是我说假设的原因:)因为许多人仍然将其讨论为 Angular 2
猜你喜欢
  • 2016-04-16
  • 2017-05-23
  • 2021-10-08
  • 1970-01-01
  • 2019-02-26
  • 1970-01-01
  • 2017-04-02
  • 2021-12-22
相关资源
最近更新 更多