【问题标题】:Passing variable from @Injectable to Component将变量从@Injectable 传递给组件
【发布时间】:2017-02-09 16:30:45
【问题描述】:

在本段下方的代码块中,您可以看到Twilio.Device.incoming,我将this.connection 设置为conn。

@Injectable()
    export class BaMsgCenterService {
        public getData;
        public incomingCall = false;
        public connection;

        constructor(private http: Http) {
            this.initTwilio();

            Twilio.Device.ready(function (device) {
                self.incomingCall = true;
                $(".card-title").text("Ready to receive incoming calls!");
            });

            Twilio.Device.incoming(function (conn) {
               console.log(conn.status);
               this.incomingCall = true;
               this.connection = conn;
            });
            //other functions
         }
    }
}

比我有一个组件类:

import {Component} from '@angular/core';
import { Http } from '@angular/http';

import {BaMsgCenterService} from './baMsgCenter.service';

@Component({
   selector: 'ba-msg-center',
   providers: [BaMsgCenterService],
   styleUrls: ['./baMsgCenter.scss'],
   templateUrl: './baMsgCenter.html'
})
export class BaMsgCenter {
   public connection;

   constructor(private _baMsgCenterService:BaMsgCenterService) {
      this.connection = this._baMsgCenterService.connection;
   }
   pickup() {
       this.connection.accept();
  }

}

在 html 代码中我有一个(click)="pickup()"

但是,当我单击它时,它说 conn 不存在。

inline template:63:10 caused by: Cannot read property 'accept' of undefined

我想让拾取功能工作,它必须能够在拾取功能中使用 conn(或 this.connection)。我认为 Twilio.Device 稍后执行(它是一个 API)...

【问题讨论】:

    标签: javascript jquery angular typescript twilio


    【解决方案1】:

    这里是 Twilio 开发者宣传员。

    当您在构造函数中设置this.connection = this_baMsgCenterService.connection 时,您并没有将两个变量绑定在一起,您只是将this.connection 指向同一位置this._baMsgCenterService.connection is pointing, which isundefinedat the time. Whenthis._baMsgCenterService.connectionis updated it doesn't changethis。连接`。

    这是一个更简单的例子:

    var a, b;
    a = b = "foo";
    b = "bar";
    console.log(a); // "foo";
    console.log(b); // "bar";
    

    您需要继续参考消息中心服务的连接。您可以使用实例方法而不是属性来执行此操作。

    类似:

    export class BaMsgCenter {
       constructor(private _baMsgCenterService:BaMsgCenterService) {}
    
       pickup() {
         this.connection().accept();
       }
    
       connection() {
         this._baMsgCenterService.connection;
       }
    }
    

    让我知道这是否有帮助。

    编辑

    我仍然认为我回答了一半的问题,但是关于事件中this 上下文的答案也是正确的。

    【讨论】:

    • 是的,但他使用了错误的语言语法或错误的语言语义,具体取决于您如何看待它,所以这无济于事。
    • 我想我已经回答了您的回答解决了第一个问题后会出现的问题。 :)
    • 还不错 ;-]
    • 谢谢@philnash,您的回答再次解决了我的挑战。
    【解决方案2】:

    使用

    (conn) => {
    

    而不是

    function (conn) {
    

    还将所有其他出现的function 更改为箭头函数样式,否则this. 不会像您期望的那样指向服务或组件类。

    【讨论】:

    • 这在这里会有所帮助,但有时您实际上需要使用 function 来与某些设计不佳的 API 对话。幸运的是,这种情况很少见
    【解决方案3】:

    你打错了this。当使用function 语法时,this 动态绑定到调用的目标,也就是说,它绑定到在用作方法时调用函数的对象。你有两个选择。

    别名this在闭包中使用局部变量:

    var that = this;
    
    takesAFunction(function (value) {
      that.prop = value;
    });
    

    如果您的目标是现代版本的 NodeJS 或现代浏览器,或者您可以访问转译器;例如 TypeScript、Babel 或 Traceur;只需使用 ES2015 箭头函数:

    takesAFunction(value => {
      this.prop = value;
    });
    

    箭头函数内部this 是静态作用域的,也称为词法作用域,就像语言中的所有其他标识符一样。

    第二种方法可以使代码更清晰,并且应该在可用的情况下优先使用。

    【讨论】:

      【解决方案4】:

      一个错误是基础服务懒惰地设置了connection。在构造函数/初始化中它还不存在,因此初始化为未定义。我猜你在这里开始一个异步操作来获取它,并在回调中将它存储在服务中:

      Twilio.Device.incoming(function (conn) {
          console.log(conn.status);
          this.incomingCall = true;
          this.connection = conn;
      });
      

      您现在可能需要做的是在 BaMsgCenter 中等待,直到连接可用。例如。仅当连接存在时才创建 BasMsgCenter。或者通过在基础服务中将其设置为 Promise 或添加另一个表示可用性的承诺,从 MsgCenter 订阅此连接,并且仅在分配后才使用连接。如果你能保证 pickup 只在之前分配连接时被调用,那就没有必要了。

      另一个错误就像 Günter Zöchbauer 也指出 this 并没有真正指向您的 BaMsgCenterService 类的实例,这可以通过使用箭头函数来修复。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-09-15
        • 2020-07-23
        • 2021-11-06
        • 1970-01-01
        • 2017-05-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多