简体   繁体   English

如何在角度6中捕获第三方库中的数据?

[英]How to capture data inside third party library in angular 6?

I've been banging my head trying to solve an issue regarding this problem of capturing data from a 3rd party library. 我一直在努力解决与从第三方库捕获数据有关的问题。

Library used is Pushfyi: https://docs.pushfyi.com/ 使用的库是Pushfyi: https ://docs.pushfyi.com/

room.component.ts: room.component.ts:

1| messages = [];
2| 
3| pushfyi.publish('test', { message : message });
4|
5| pushfyi.subscribe('test', function(evnt){
6|  let json = JSON.parse(evnt);
7|  this.messages.push(json.message);
8|});

After running the code it gives me an error message: ERROR TypeError: Cannot read property 'push' of undefined 运行代码后,它给我一条错误消息: ERROR TypeError:无法读取未定义的属性“ push”

I understand that this.messages does not exist inside the function, so how can I capture the json.message to have it show on my room.component.html in my view 我知道this.messages在函数内部不存在,所以我如何捕获json.message以使其在我的view.room.component.html中显示


UPDATE: Here is the complete room.component.ts and on line 32 is where I get the error: ERROR TypeError: Cannot read property 'push' of undefined 更新:这是完整的room.component.ts,第32行是我收到错误的位置:错误TypeError:无法读取未定义的属性“ push”

  1 import { Component, OnInit, NgZone, ChangeDetectorRef} from '@angular/core';
  2 import { Router, ActivatedRoute, ParamMap } from '@angular/router';
  3 import { PushfyiService } from './../pushfyi.service';
  4     
  5 @Component({
  6   selector: 'app-room',                                                        
  7   templateUrl: './room.component.html',                                        
  8   styleUrls: ['./room.component.css']
  9 })
 10 export class RoomComponent implements OnInit {                                 
 11 
 12   roomId = '';
 13   messages = ["test"];
 14 
 15   constructor(private route: ActivatedRoute, private ref: ChangeDetectorRef, private pushfyiService: PushfyiService) { }
 16 
 17   ngOnInit() {
 18     this.route.paramMap.subscribe((params: ParamMap) => {
 19       this.roomId = params.get('id');  
 20 
 21       this.pushfyiService.init(this.roomId);
 22     });
 23   }
 24 
 25   sendChange(value){
 26     this.pushfyiService.publish('pushfyi-component', value);
 27     this.pushfyiService.pushfyi.subscribe('pushfyi-component', this.setMessage);
 28   }
 29 
 30   setMessage(evnt){
 31     let json = JSON.parse(evnt);
 32     this.messages.push(json.data);
 33   }
 34 
 35 }

You're not binding your event callback to the local scope, that's why your callback does not know the messages array : 您没有将事件回调绑定到本地范围,这就是为什么您的回调不知道messages数组的原因:

5| pushfyi.subscribe('test', function(evnt){
6|  let json = JSON.parse(evnt);
7|  this.messages.push(json.message);
8|});

should be 应该

5| pushfyi.subscribe('test', evnt => {
6|  let json = JSON.parse(evnt);
7|  this.messages.push(json.message);
8|});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM