【问题标题】:Cannot read property of undefined when calling the function with setInterval in Angular [duplicate]在Angular中使用setInterval调用函数时无法读取未定义的属性[重复]
【发布时间】:2019-12-18 10:19:45
【问题描述】:

调用函数时没有任何问题,但是在 setInterval 中调用它时,所以每秒继续调用它给我一个错误:无法读取服务上未定义的属性!

 constructor(private route: ActivatedRoute,private 
 conversationService:ConversationService) {
 }


 ngOnInit() {
 this.sender = this.route.snapshot.paramMap.get("username");
 this.receiver = sessionStorage.getItem("username");
 setInterval(
 function()
 { 
   this.conversationService.
   getTheConversation(this.receiver,this.sender).subscribe(
     data=>this.result=data)
   },1000);
 } 

错误: 错误类型错误:无法读取未定义的属性“getTheConversation”

【问题讨论】:

  • 为什么不使用 rxjs 定时器?有些像timer(0,1000).pipe(switchMap(()=>{return this.conversationService.getTheConversation(this.receiver,this.sender)})).subscribe(data=>this.result=data)

标签: javascript angular typescript ecmascript-6


【解决方案1】:

试试

 ngOnInit() {
 this.sender = this.route.snapshot.paramMap.get("username");
 this.receiver = sessionStorage.getItem("username");
 setInterval(()=>
 { 
   this.conversationService.
   getTheConversation(this.receiver,this.sender).subscribe(
     data=>this.result=data)
   },1000);
 } 

使用胖箭头 => 来维护this 范围。当您声明一个新的 function 时,它会创建自己的 this

【讨论】:

  • 你也可以使用 'rxjs' Timer 和 switchMap。
【解决方案2】:

函数 setInterval 指向不同的 this 对象,

这样做的正确方法是,

const newThis = this;
setInterval(
 function()
 { 
   newThis.conversationService.
   getTheConversation(newThis.receiver,newThis.sender).subscribe(
     data=>newThis.result=data)
   },1000);

点击链接了解更多其他方法https://stackoverflow.com/a/7890978/11914056

【讨论】:

    猜你喜欢
    • 2020-03-05
    • 2017-05-23
    • 2018-10-26
    • 2018-09-11
    • 2014-08-20
    • 1970-01-01
    • 1970-01-01
    • 2018-01-14
    相关资源
    最近更新 更多