Angular 2+并从htttp获取数据到服务中的行为主体

时间:2018-06-20 13:50:48

标签: angular

我已经创建了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;
    });
}

2 个答案:

答案 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);
        });
}