[英]angular2, interface TypeScript, ERROR ReferenceError: base is not defined
我剛剛開始學習Angular2,我做了一些教程。 我必須基於接口顯示服務中的數據。 而且我有問題。
我認為問題來自TypeScript界面,但是,因為這對我來說是新事物,所以我什至不知道在哪里尋找錯誤。
currency.ts(接口):
export interface ICurrency {
base: string;
date: string;
rates: object;
}
currency.service:
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應該顯示對象,但出現錯誤
AppComponent.html:1錯誤ReferenceError:未在CurrencyComponent.ngOnInit(currency.component.ts:27)的CurrencyComponent.getCurrency(currency.component.ts:22)處的CurrencyService.getCurrency(currency.service.ts:19)處定義基數)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 [作為updateDirectives](AppComponent.html:3),位於Object.debugUpdateDirectives [作為updateDirectives](core.js:14339)
而且我真的不知道我哪里出了錯。 我在app.modules中添加了提供程序CurrencyService。 請幫忙,我想學習Angular2,所以我想了解我的錯誤。
您有2個錯誤,我可以看到。
this.currency
但currency
未定義為CurrencyComponent
類型的成員,因此該組件甚至不應進行轉換。 getCurrency
()的末尾添加return語句(或在創建列表后在組件中添加第二個賦值調用)。 帶有修復程序的關注代碼。 我省略了與該問題無關的代碼。
currency.service:
@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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.