编辑:我已经解决了这个问题。请参阅下面的答案,因为它可能有助于某人。如果你知道更好的答案,请发布! :)Angular 2 Http,RxJS无法读取undefined属性'unsubscribe'
我工作的一个Angular 2 Universal API缓存,并有一个这样的ApiService:
import {Http} from '@angular/core';
export class ApiService {
constructor(private http: Http, private cache: CacheService)
}
get(url) {
if (cache_data) {
//Create new observable from scratch
return new Observable(sub => {
sub.next(cache_data);
});
} else {
//Use Angular 2's Http service, which creates an Observable for me
return this.http.get(url)
.map(res => res.json())
.catch(err => throw err);
}
}
在另一个服务,在这里我订阅它,我有:
import {ApiService} from './api/api.service';
export class ConsumerService {
constructor(apiService: ApiService) {}
let sub = this.apiService.get('www.example.com')
.subscribe(data => {
console.log(data);
sub.unsubscribe();
})
}
如果请求的数据不在缓存中,并且服务器必须为其发出http请求,则上述代码完美工作。但是,如果缓存中的数据为,则会出现以下错误:Cannot read property 'unsubscribe' of undefined
未定义,当然是指我的变量sub
。
我最初的想法是,我在缓存中创建的Observable类型与Angular 2的Http observable是不同的,因此会产生错误。我试过这个,但没办法确认。任何帮助表示赞赏。
你为什么要在'next'块中调用'unsubscribe'?此外,还有一个单一项目“Observable.of(cached_data)”的创建方法。 – paulpdaniels
你也可以在'sub.next()'后面调用'sub.complete()'完成在完成时自动退订的observable。 – tomastrajan