这是我的服务文件
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]属性'subscriof'在类型'typeof Observable'
上不存在
另一个错误说
[ts]参数'message'隐式具有'any'类型。 (参数) 消息:任何
答案 0 :(得分:3)
我认为你有一个小错字。改变这个:
return Observable;
到此:
return observable;