我已经创建了planets.service,我想从http获取数据,然后将其放入behaviourSubject。下一步,我想在不同组件中订阅planets $。我遇到错误:
AppComponent_Host.html:1 ERROR TypeError: Cannot read property 'subscribe' of undefined
有人知道怎么解决吗?
Planets.service.ts:
export class PlanetsService {
private _planetsUrl: string = "https://swapi.co/api/planets/?format=json";
planets$: Subject<any>;
constructor(private _http: Http) {
this.getPlanetsFromUrl().subscribe(planets => {
this.planets$ = new BehaviorSubject<any>(planets);
console.log(planets);
});
}
getPlanetsFromUrl() {
return this._http.get(this._planetsUrl)
.map( (response: Response) => response.json().results )
}
}
App.component.ts:
planets: any[];
ngOnInit() {
this._planetsService.planets$.subscribe(planets => {
this.planets = planets;
});
}
答案 0 :(得分:1)
planets$: Subject<any> = new BehaviorSubject<any>()
constructor(private _http: Http) {
this.getPlanetsFromUrl().subscribe(planets => {
this.planets$.next(planets);
console.log(planets);
});
}
您正在subscribe
回调中分配主题。发生在组件ngOnInit
之后的 ,因为它是HTTP响应。
在创建服务时,将新的BehaviorSubject
分配给属性,然后调用next
发出值。
答案 1 :(得分:0)
您应该创建Subject
的实例并将其分配给planet$
。您所做的只是创建了reference
,而不是instance
Subject
planets$: Subject<any> = new Subject<any>();
在ngOnInit()
方法返回之前,您在this.getPlanetsFromUrl()
中的代码将运行。这意味着您在分配Subject
对象之前尝试访问。因此,最好在声明期间创建实例,如上所示。
只需从您的服务文件中发出this.planets$.next(planets);
constructor(private _http: Http) {
this.getPlanetsFromUrl().subscribe(planets => {
this.planets$.next(planets);
console.log(planets);
});
}