【发布时间】:2018-01-05 23:01:31
【问题描述】:
这是我的服务文件
import {Injectable} from '@angular/core';
import {Subject} from 'rxjs/Subject';
import {Observable} from 'rxjs/Observable';
import * as io from 'socket.io-client';
export class chatService{
private url = 'http://localhost:8000'
private socket:any;
sendMessage(message:string){
this.socket.emit('add-message', message);
}
getMessages(){
let observable = new Observable(( observer:any)=>{
this.socket = io(this.url);
this.socket.on('message',(data:any)=>{
observer.next(data);
});
return () => {
this.socket.disconnect();
}
})
return Observable;
}
}
这是我的订阅方法显示错误
import { Component } from '@angular/core';
import {chatService} from '../../services/chat.service';
import { OnInit, OnDestroy } from '@angular/core/src/metadata/lifecycle_hooks';
import { Message } from '@angular/compiler/src/i18n/i18n_ast';
import * as io from 'socket.io-client';
@Component({
moduleId:module.id,
selector: 'chat',
templateUrl: `chat.componets.html`,
})
export class chatComponent implements OnInit, OnDestroy {connection: any;
name = 'Angular';
messages: any = [];
message: string;
constructor(private _chatService:chatService){
}
sendMessage(){
this._chatService.sendMessage(this.message);
this.message = '';
}
ngOnInit(){
this.connection = this._chatService.getMessages().subscribe(message=> {
console.log(message);
this.messages.push(message);
});
}
ngOnDestroy(){
this.connection.unsubscribe();
}
}
在我必须调用getMessage() 的服务文件中,以及何时订阅我调用该服务方法getMessage() 的另一个类中的方法。它显示错误
[ts] 类型“typeof Observable”上不存在属性“subscribe”
另一个错误说
[ts] 参数 'message' 隐含地具有 'any' 类型。 (范围) 消息:任何
【问题讨论】: