Angular 2 服务数据绑定

Angular 2 Service Data Binding

当我的应用程序首次启动时,我希望 player.service 发出 HTTP 请求并将数据作为变量保存在我的服务中以供我的组件访问。我的服务使请求正常并且数据确实保存了,但我的视图永远不会更新。

在我的 playerlist.component 中,我注入了访问变量的服务,但我无法获取数据。我想这是因为我需要做所有这些可观察到的事情才能实现它。

我想要的只是我视图中的列表在页面加载时填充并确保我所有未来的组件都可以访问单一数据源以防止多个 http 请求。

在我的 app.component 中,我确实包含 player.service 并将其放入提供程序中...如果重要的话。

player.service

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';

@Injectable()
export class PlayerListService {

    public playerListData;

    constructor(private http:Http) {
        this.getPlayerData().subscribe(
            data => this.playerListData = data
        );
    }

    getPlayerData = ():Observable<any> => {
      return this.http.get('my-api').map(response => response.json())
    }
}

玩家列表组件

import { Component, OnInit } from '@angular/core';
import { PlayerListService } from '../shared/index';

@Component({
    selector: 'app-player-list',
    templateUrl: './player-list.component.html',
    styleUrls: ['./player-list.component.scss']
})
export class PlayerListComponent implements OnInit {

    public playerList;

    constructor(private playerListService:PlayerListService) {}

    ngOnInit() {
        this.playerList = this.playerListService.playerListData;
    }
}

问题是当组件的 OnInit 运行时您的数据尚未获取。

您可以做的是返回 playerListData 的 Observable 并订阅该 Observable 以获取实际值。

服务

public playerListData: Subject<any> = new Subject<any>();

constructor(private http:Http) {
    this.getPlayerData().subscribe(
        data => this.playerListData.next(data)
    );
}

分量

在您的组件中,您可以在模板中使用 async 管道

{{ playerListService.playerListData | async }}

ngOnInit() {
    this.playerListService.playerListData
        .subscribe(data => this.playerList = data);
}

这里出现错误,您没有选择此服务的提供商

@Component({
selector: 'app-player-list',
templateUrl: './player-list.component.html',
styleUrls: ['./player-list.component.scss'],
providers: [PlayerListService] //<--- add this line on your component

})