This question是类似的,但即使在阅读它和一些教程和示例之后我仍然无法使其工作。 Angular 2似乎有很多不同的风格和方法。
我正在尝试使用Angular 2组件来侦听将通过Web套接字接收推文的服务。
现在我只想获得我在套接字上收到的最新推文。
推文到达套接字,我的控制台日志显示每次“收到消息”时我都在“设置消息”。推文是一个对象,带有一个包含twit字符串的键“message”。
组件中的“更改”日志消息未显示,因此我假设订阅主题时出现问题。
我只是无法发现它,但是,我已经阅读了一些Angular documentation并尝试了这些模式,但我仍然无法使其正常工作。
我有这项服务:
import { Injectable } from '@angular/core';
import * as Rx from "rxjs/Rx";
declare var Phoenix: any;
@Injectable()
export class PhoenixChannelService {
socket: any;
private myMessage: string;
private messageSubject: Rx.Subject<string> = new Rx.Subject<string>();
constructor() {
this.socket = new Phoenix.Socket("ws://localhost:4000/socket", {
logger: ((kind, msg, data) => { console.log(`${kind}: ${msg}`, data) }),
transport: WebSocket
});
this.socket.connect();
this.socket.onError( () => console.log("there was an error with the connection!") );
this.socket.onClose( () => console.log("the connection dropped") );
}
public subscribeToKeyword(submittedKeyword) {
let channel = this.socket.channel("keyword:" + submittedKeyword, {token: "foo"})
var me = this;
channel.on("tweet", function(msg) {
console.log("Got message", msg);
me.setMessage(msg.message);
});
channel.join()
.receive("ok", ({messages}) => console.log("catching up", messages) )
.receive("error", ({reason}) => console.log("failed join", reason) )
.receive("timeout", () => console.log("Networking issue. Still waiting...") )
}
public getMessage(): Rx.Observable<string> {
return this.messageSubject.asObservable();
}
setMessage(message: string): void {
console.log("Setting message");
this.myMessage = message;
this.messageSubject.next(message);
}
}
这是我的组成部分:
import { Component } from '@angular/core';
import { PhoenixChannelService } from './app.phoenix_channels.service';
@Component({
selector: 'watch-stream',
templateUrl: 'templates/stream.html',
providers: [PhoenixChannelService]
})
export class StreamComponent {
currentMessage: string;
constructor(private phoenixChannel: PhoenixChannelService) {
phoenixChannel.getMessage().subscribe((newMessage: string) => {
console.log("change");
this.currentMessage = newMessage;
});
console.log('Constructed the stream component');
}
}