当在Angular 7中遇到“undefined”变量的问题时,可以尝试以下解决方法:
示例代码:
export class MyComponent {
myVariable: any; // 声明变量
ngOnInit() {
this.myVariable = 'Hello world';
console.log(this.myVariable);
}
}
示例代码:
export class MyComponent {
myVariable: any = ''; // 为变量赋初始值
ngOnInit() {
this.myVariable = 'Hello world';
console.log(this.myVariable);
}
}
示例代码:
import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
@Component({
selector: 'my-component',
template: `{{ myVariable }}
`
})
export class MyComponent {
myVariable: any;
constructor(private http: HttpClient) {}
ngOnInit() {
this.http.get('https://api.example.com/data')
.subscribe((data) => {
this.myVariable = data;
console.log(this.myVariable);
});
}
}
通过检查变量声明、初始化和赋值来源,应该能够解决Angular 7中“undefined”变量的问题。