angular2,接口 TypeScript,错误引用错误:未定义基



我刚开始学习Angular2,我做了一些教程。我必须根据接口显示来自服务的数据。我有问题。

我认为问题来自TypeScript界面,但是,因为它对我来说是新事物,我什至不知道在哪里寻找错误。

货币.ts(接口):

export interface ICurrency {
base: string;
date: string;
rates: object;
}

货币服务:

import { Injectable } from '@angular/core';
import { ICurrency } from './currency';

@Injectable()
export class CurrencyService {
currency:Array<ICurrency>;
getCurrency(){
this.currency = [{
base: "base1111",
date: "11111",
rates: {a:"a",b:"b"}
},
base: "base2222",
date: "222222",
rates: {a:"c",b:"d"}
}]
};
}

货币.组件

import { Component, OnInit } from '@angular/core';
import { CurrencyService } from './currency.service';
import { ICurrency } from './currency';
@Component({
selector: 'app-currency',
template: `
<p>
currency works!
</p>
`,
styles: []
})
export class CurrencyComponent implements OnInit {
constructor(private _currencyList: CurrencyService) { }    
getCurrency(){
this.currency = this._currencyList.getCurrency();
console.log(this.currency);
}
ngOnInit(){
this.getCurrency();
}
}

Consola 应该显示该对象,但我收到错误

应用组件.html:1 错误引用错误:未定义基数 at CurrencyService.getCurrency (currency.service.ts:19) at CurrencyComponent.getCurrency (currency.component.ts:22) at CurrencyComponent.ngOnInit (currency.component.ts:27) at checkAndUpdateDirectiveInline (core.js:12095) at checkAndUpdateNodeInline (core.js:13598) at checkAndUpdateNode (core.js:13541) at debugCheckAndUpdateNode (core.js:14413) at debugCheckDirectivesFn (core.js:14354) at Object.eval [as updateDirectives] (AppComponent.html:3) at Object.debugUpdateDirectives [as updateDirectives] (core.js:14339)

我真的不知道我在哪里犯了错误。我在应用程序模块中添加了提供程序 CurrencyService。请帮忙,我想学习Angular2,所以我想了解我的错误。

我可以看到您有 2 个错误。

  1. 您正在使用this.currencycurrency未定义为CurrencyComponent类型中的成员,此组件甚至不应转译。
  2. 您的服务方法实际上并不返回列表,而是将其分配给一个字段。如果要在组件中捕获结果,请在方法getCurrency() 的末尾添加 return 语句(或在创建列表后在组件中添加第二个赋值调用)。

带有修复的感兴趣代码。我省略了与问题无关的代码。

货币服务:

@Injectable()
export class CurrencyService {
currency:Array<ICurrency>;
getCurrency() : Array<ICurrency> {
this.currency = [{
base: "base1111",
date: "11111",
rates: {a:"a",b:"b"}
}, {
base: "base2222",
date: "222222",
rates: {a:"c",b:"d"}
}];
return this.currency;
}
}

货币.组件

export class CurrencyComponent implements OnInit {
currency:Array<ICurrency>;
constructor(private _currencyList: CurrencyService) { }    
getCurrency(){
this.currency = this._currencyList.getCurrency();
console.log(this.currency);
}
ngOnInit(){
this.getCurrency();
}
}

最新更新