首页 > 解决方案 > (this) 关键字在 Angular 中不起作用

问题描述

我想知道为什么 'this' 关键字在 Angular 项目中的某些函数中不起作用。这是我的意思的一个小演示

在 AppComponent.ts 文件中,我使用 ngOnInit 生命周期钩子中的“this”调用了一个服务方法。这很好用,但是当我尝试在 setInterval() 方法中使用相同的关键字“this”调用相同的服务方法时,出现错误。所以我想知道为什么'this'在某些方法中起作用而在其他方法中不起作用?

这是 AppComponent.ts 文件

import { ServerService } from './-server.service';
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})

export class AppComponent {
  constructor(private _server: ServerService){}

 ngOnInit(){
   // this works fine
   this._server.getUSSDTransactionStatus().subscribe(resp=>{ 
     console.log('resp: ', resp); // I got response
   });

  let interval = setInterval(async function(){
     // this is throwing error
     this._server.getUSSDTransactionStatus().subscribe(resp=>{
       console.log('resp: ', resp)
     });
   }, 5000);
 }
}

这是我的服务

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class ServerService {
  constructor(private _http: HttpClient) { }

  getUSSDTransactionStatus(){
    return this._http.get('http://********');
 }
}

标签: angularthis

解决方案


原因是 setInterval 内部的回调函数处于不同的词法环境中

在 ES6+ 中,函数可以使用 => 来定义。这是为了使函数内的代码与函数共享相同的范围。

setInterval(() => {
  this._server.getUSSDTransactionStatus().subscribe(resp=>{
       console.log('resp: ', resp)
     });
   }, 5000);
});

否则您可以在使用之前为其分配一个变量例如

    const _self = this;
let interval = setInterval(async function(){
     // this wont throw error now
     _self._server.getUSSDTransactionStatus().subscribe(resp=>{
       console.log('resp: ', resp)
     });
   }, 5000);
 }

推荐阅读