无法读取 属性 Typescript Angular 5 中未定义的某些值
Cannot read property somevalue of undefined in Typescript Angular 5
我在使用 Angular 5 服务时遇到以下问题,你能帮我看看下面的代码有什么问题吗
我已经回答了以下问题,但没有帮助我
- Question 3
我只想初始化class中的值并在方法
中使用它
虽然我已经在 class 中定义了 url 值,但是对于 console.log(this.url);
行,我得到的错误是 Cannot read property 'url' of undefined
@Injectable()
export class OwnService {
public accessTokenvalue = '';
public url = 'https://www.someurl.com/id=';
constructor(private hp: HelpService) {
}
public gethpPhotos() {
this.hp.login()
.then(function (response: LoginResponse) {
console.log(response);
console.log(this.url);
})
.catch((error: any) => console.error(error));
}
}
你只需要用箭头函数替换function (response: Response)
。每个 function
创建它的范围,它在其中引用 this
。箭头函数将保留 this
.
.then((response: LoginResponse) => {
console.log(response);
console.log(this.url);
})
您可以使用 'url' 所在的上下文进行解析:
public gethpPhotos() {
var that = this; // outer context
this.hp.login()
.then(function (response: LoginResponse) {
console.log(response);
console.log(that.url); // <<<< changed to that.url for the outer context
})
.catch((error: any) => console.error(error));
}
在您的代码中,this 指的是 http 请求的上下文。为了访问组件变量,使用箭头函数
this.hp.login()
.then(response: LoginResponse) => {
this.answerList = response;
console.log(this.url);
)
我在使用 Angular 5 服务时遇到以下问题,你能帮我看看下面的代码有什么问题吗
我已经回答了以下问题,但没有帮助我
- Question 3
我只想初始化class中的值并在方法
中使用它虽然我已经在 class 中定义了 url 值,但是对于 console.log(this.url);
Cannot read property 'url' of undefined
@Injectable()
export class OwnService {
public accessTokenvalue = '';
public url = 'https://www.someurl.com/id=';
constructor(private hp: HelpService) {
}
public gethpPhotos() {
this.hp.login()
.then(function (response: LoginResponse) {
console.log(response);
console.log(this.url);
})
.catch((error: any) => console.error(error));
}
}
你只需要用箭头函数替换function (response: Response)
。每个 function
创建它的范围,它在其中引用 this
。箭头函数将保留 this
.
.then((response: LoginResponse) => {
console.log(response);
console.log(this.url);
})
您可以使用 'url' 所在的上下文进行解析:
public gethpPhotos() {
var that = this; // outer context
this.hp.login()
.then(function (response: LoginResponse) {
console.log(response);
console.log(that.url); // <<<< changed to that.url for the outer context
})
.catch((error: any) => console.error(error));
}
在您的代码中,this 指的是 http 请求的上下文。为了访问组件变量,使用箭头函数
this.hp.login()
.then(response: LoginResponse) => {
this.answerList = response;
console.log(this.url);
)