如何通过Subject / Observable将数据从组件传输到另一个组件?

时间:2016-08-26 11:20:43

标签: angularjs

我找到了一个有趣的例子,说明如何使用服务中的Subject / Observable将数据从一个组件传输到另一个组件:

http://plnkr.co/edit/yMBoVkxohwhPig5COgkU?p=preview

我发现它类似于Angular 1.X的广播事件。但我注意到订阅数据更改只能组成数据变化。我需要以某种方式修改此示例以在另一个组件更改后在一个组件中获取数据。 Console.log不显示任何错误,但数据传输不起作用。有人可以帮忙吗?

服务:

@Injectable()
export class ClientsService {

    private _client$: Subject<Client>;
    private _clients$: Subject<Client[]>;

    constructor(private http: Http) {
        this._client$ = <Subject<Client>>new Subject();
        this._clients$ = <Subject<Client[]>>new Subject();
    }

    getClients(): Promise<Client[]> {
        return this.http.get('api/Client')
            .toPromise()
            .then(res => {
                this._clients$.next(res.json());
                return res.json();
            })
            .catch(this.handleError);
    }

    get client$() {
        return this._client$.asObservable();
    }

    get clients$() {
        return this._clients$.asObservable();
    }

    clientChangeBroadcast(objClient: Client) {
        this._client$.next(objClient);
    }

    clientsChangeBroadcast(arrClients: Client[]) {
        this._clients$.next(arrClients);
    }

    private handleError(error: any): Promise<any> {
        return Promise.reject(error.message || error);
    }

第一部分:

@Component({
    selector: 'app',
    templateUrl: './app/app.component.html'
})
export class AppComponent implements OnInit {
    clients: Client[];

    constructor(public clientsService: ClientsService) {
        this.clients = [];

    }

    ngOnInit() {

    }

    loadClients() {
        this.clientsService.getClients().then(clients => {
            this.clients = clients;
            this.clientsService.clientsChangeBroadcast(clients);
        });
    }

    selectClient(objClient: Client) {
        this.clientsService.getClients();
        this.clientsService.clientChangeBroadcast(objClient);
    }
}

第二部分:

export class TestComponent implements OnInit {
    client: Observable<Client>;
    clients: Observable<Client[]>;

    constructor(private clinetsService: ClientsService) {

    }

    ngOnInit() {

            //this.clinetsService.getClients();

            this.client = this.clinetsService.client$;
            this.clients = this.clinetsService.clients$;

            this.clinetsService.client$.subscribe(value => {
                // try to get changes here

            });

            this.clinetsService.clients$.subscribe(value => {
                // try to get changes here

            });
    }

    reLoadClients() {
        this.clinetsService.getClients();
    }

}

在'First component'更改数据后,我试图在'Second component'中获取数据changinf。当我点击“第一个组件”中的“selectClient”方法的按钮时,我希望数据传输与服务一起,并且我捕获变化ob'第二个组件' - &gt;它不起作用。当来自“第二个组件”时,我按下“reLoadClients”数据传输服务的按钮,我在“第二个组件”上捕获所有订阅功能的更改。

0 个答案:

没有答案