这是一个与打字稿范围有关的问题。如果listofstuff常量在类结束括号之外,则它可以工作,但如果它在括号内
则不行例如,此代码不起作用:
import {Injectable} from '@angular/core'
@Injectable()
export class EventListService{
getEvents(){
return listofstuff
}
const listofstuff = [
{name:'Angular Connect', date: '9/26/2036', time: '10am', location: {address: '1 London Rd', city: 'London', country: 'England'}},
{name:'ng-nl', date: '4/15/2037', time: '9am', location: {address: '127 DT ', city: 'Amsterdam', country: 'NL'}},
{name:'ng-conf 2037', date: '4/15/2037', time: '9am', location: {address: 'The Palatial America Hotel', city: 'Salt Lake City', country: 'USA'}},
{name:'UN Angular Summit', date: '6/10/2037', time: '8am', location: {address: 'The UN Angular Center', city: 'New York', country: 'USA'}},
]
}
但这有效:
import {Injectable} from '@angular/core'
@Injectable()
export class EventListService{
getEvents(){
return listofstuff
}
}
const listofstuff = [
{name:'Angular Connect', date: '9/26/2036', time: '10am', location: {address: '1 London Rd', city: 'London', country: 'England'}},
{name:'ng-nl', date: '4/15/2037', time: '9am', location: {address: '127 DT ', city: 'Amsterdam', country: 'NL'}},
{name:'ng-conf 2037', date: '4/15/2037', time: '9am', location: {address: 'The Palatial America Hotel', city: 'Salt Lake City', country: 'USA'}},
{name:'UN Angular Summit', date: '6/10/2037', time: '8am', location: {address: 'The UN Angular Center', city: 'New York', country: 'USA'}},
]
来自面向对象的背景(C#和一些java),这对我来说很奇怪。谁能解释一下这里发生了什么?即使在第一个示例中使用“this”关键字也不起作用...
答案 0 :(得分:3)
您不能将const
关键字用于类属性。相反,类属性只能使用public
,private
,readonly
和protected
修饰符进行标记。
import { Injectable } from '@angular/core'
@Injectable()
export class EventListService {
readonly listofstuff: any[] = [
{ name: 'Angular Connect', date: '9/26/2036', time: '10am', location: { address: '1 London Rd', city: 'London', country: 'England' } },
{ name: 'ng-nl', date: '4/15/2037', time: '9am', location: { address: '127 DT ', city: 'Amsterdam', country: 'NL' } },
{ name: 'ng-conf 2037', date: '4/15/2037', time: '9am', location: { address: 'The Palatial America Hotel', city: 'Salt Lake City', country: 'USA' } },
{ name: 'UN Angular Summit', date: '6/10/2037', time: '8am', location: { address: 'The UN Angular Center', city: 'New York', country: 'USA' } },
];
getEvents() {
return this.listofstuff;
}
}
您可以使用listofstuff
关键字访问this
类属性。 Example
您可以在官方documentation中阅读有关Typescript类的更多信息。请记住,默认情况下,属性和没有标识符的成员会标记为public
。来自文档:
在TypeScript中,默认情况下每个成员都是公开的。
希望这有帮助!