Angular 创建自定义的可观察对象

Angular 创建自定义的可观察对象,angular,angular2-observables,Angular,Angular2 Observables,是否有可能(且正确)创建一个自定义的可观察对象? 例如,如果缓存中有数据,我希望在发出http请求之前创建自定义可观察对象: 我的请求: private device: Device; getDeviceById(deviceId): Observable<Device> { if(this.device._id == deviceId) { let myObservable = new Observable('with my device');

是否有可能(且正确)创建一个自定义的可观察对象? 例如,如果缓存中有数据,我希望在发出http请求之前创建自定义可观察对象:

我的请求:

private device: Device;
getDeviceById(deviceId): Observable<Device> {
    if(this.device._id == deviceId) {
        let myObservable = new Observable('with my device'); 
        return myObservable;
    } else return this.http.get('/api/device/get/'+deviceId)
                .map(res => res.json())
                .catch(this.handleError);
}
专用设备:设备;
getDeviceById(deviceId):可观察{
if(this.device.\u id==deviceId){
让myObservable=新的可观察对象(“使用我的设备”);
返回可观察;
}否则返回此.http.get('/api/device/get/'+deviceId)
.map(res=>res.json())
.接住(这个.把手错误);
}

谢谢,是的,您可以创建一个主题,如答案中所述,作为可观察的主题,并在缓存中有数据时使用它。

您可以执行以下操作:

getDeviceById(deviceId): Observable<Device> {
if(this.authProvider == deviceId) {
    return Observable.create(observer => {
        observer.next("something");
        observer.complete();
    });
} else return this.http.get('/api/device/get/'+deviceId)
            .map(res => res.json())
            .catch(this.handleError);
getDeviceById(deviceId):可观察{
if(this.authProvider==deviceId){
返回可观察的。创建(观察者=>{
下一步(“某物”);
observer.complete();
});
}否则返回此.http.get('/api/device/get/'+deviceId)
.map(res=>res.json())
.接住(这个.把手错误);

您可以执行以下操作:

var button = document.querySelector('button');

var subscription = Rx.Observable.create(function(obs) {
  button.onclick = function(event) {
  obs.next(event);
}
.subscribe(function(value) {
   console.log(value);
},);

请参阅该链接中的更多内容:

我不明白问题出在哪里。为什么不能创建自定义的可观察对象?或者您想使用可观察对象而不是
http
请求?我已经尝试过了,但返回的可观察对象不是“可观察”类型