请考虑以下示例:
MyComponent.ts
const soccerPlayer = ["Messi", "Maradona", "Lebron", "Mane"];
const myPromise = new Promise(( resolve, reject) => {
soccerPlayer.forEach( element => {
if( element.startsWith("M")) {
resolve("Thats a soccer star");
} else {
reject("Not a soccer star");
}
})
});
myPromise
.then(res => console.log(res));
.catch(err => console.log(err));
MyService.ts
export class MyComponent {
constructor(private myService: MyService) {
myService.printServiceField();
}
}
我得到以下
ERROR TypeError:“这是未定义的”
任何人都可以解释原因或为我指明正确的方向吗?如果我将myField设为@Injectable({
providedIn: 'root'
})
export class MyService {
readonly myField= 'N/A';
constructor() {}
printServiceField() {
console.log(this.myField);
}
(并用static
调用),那么它将起作用。我并不是真正在寻找解决方案(我有解决方案),而是为什么会这样。