我一直在努力解决与从第三方库中捕获数据有关的问题。
使用的库是Pushfyi:https://docs.pushfyi.com/
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|});
运行代码后,它给我一条错误消息: 错误TypeError:无法读取未定义的属性“ push”
我了解 this.messages 并不存在,所以如何捕获 json.message 使其显示在我的 room.component.html 中查看
更新: 这是完整的room.component.ts,在线 32 是我得到错误的地方:ERROR 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 }
答案 0 :(得分:2)
您没有将事件回调绑定到本地范围,这就是为什么您的回调不知道messages
数组的原因:
5| pushfyi.subscribe('test', function(evnt){
6| let json = JSON.parse(evnt);
7| this.messages.push(json.message);
8|});
应该是
5| pushfyi.subscribe('test', evnt => {
6| let json = JSON.parse(evnt);
7| this.messages.push(json.message);
8|});