【问题标题】:angular 4 function undefined when nested in http request [duplicate]嵌套在http请求中时未定义的角度4函数[重复]
【发布时间】:2018-10-12 15:56:42
【问题描述】:

我是 Angular 的新手,并试图快速学习,但我对正在发生的事情感到困惑。当我的 TS 文件被加载时,它会从 http.get 请求中获取消息列表并将它们存储在变量 conversation 中。但是,当我添加一条新消息时,它会发送到我的 API 并返回结果,但是当我尝试将消息添加到对话中时,我会收到错误

this.insertMessage 未定义

但是功能已经设置好了。请参阅下面的代码。我假设当您尝试在 .subscribe 方法的完整函数中调用函数时,您无法访问外部函数。对吗?

export class MessagePage {

  newmessage;
  conversation;

  id;
  response: {};

  ionViewWillEnter(){
    this.getMessage(this.id);
  }

  // public messageArr;
  constructor(public navCtrl: NavController, public navParams: NavParams, public messageService: MessagesProvider) {
    this.id = navParams.get('id');
  }

  addmessage(): void {
    this.messageService.addMessage(this.newmessage,this.id)
      .subscribe( 
        function(response) { console.log("Success Response" + response); this.response = response;},
        function(error) { console.log("Error happened" + error)},
        function() {     
          if(this.response.result == 200) this.insertMessage(this.response.response.message);
          else console.error(this.response);
        }
      );
  }

  getMessage(id: number): void {
    this.messageService.getMessage(id)
      .subscribe(message => this.conversation = message);
  }

  insertMessage(message): void {
    console.log('conversation:'+ this.conversation);
    this.conversation.push(message);
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad MessagePage');
  }

}

【问题讨论】:

标签: angular ionic-framework ionic3


【解决方案1】:

使用更现代的箭头函数(() => {})语法代替普通函数语法(function () {})来保留this的范围。

由于this 的范围在您的回调函数中发生了变化,this 不再指代您的MessagePage

使用箭头函数(() => {}) 语法将保留this 的范围。

用这个来修复:

addmessage(): void {
  this.messageService.addMessage(this.newmessage, this.id)
    .subscribe(
      response => this.response = response,
      error => console.log("Error happened" + error),
      () => {
        if (this.response.result == 200) 
          this.insertMessage(this.response.response.message);
        else console.error(this.response);
      }
    );
}

【讨论】:

  • 这不是 hack 在 ECMAScript 3/5 中,可以通过将 this 中的值分配给变量来解决此问题。
【解决方案2】:

您可以像下面这样简单地访问 this 的外部范围

  addmessage(): void {
     var self=this;

    this.messageService.addMessage(this.newmessage,this.id)
      .subscribe( 
        function(response) { console.log("Success Response" + response); this.response = response;},
        function(error) { console.log("Error happened" + error)},
        function() {     
          if(this.response.result == 200) self.insertMessage(this.response.response.message);
          else console.error(this.response);
        }
      );
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-26
    • 1970-01-01
    • 2019-03-22
    • 1970-01-01
    相关资源
    最近更新 更多