Search code examples
angularangular2-components

angular 4 pass data between components without input\output


I'm trying to pass data between components in angular 4. I don't want to use input\output. in Homecomponent I want to push data into service and in page2 component I want to get data from service. I just looked on way with observable and subject and I tried to implement it without success.

HomeComponent

    import { ClientService } from './../clinet-service.service';
import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'page-home',
  template: 'pages/home/home.html',
})
export class HomeComponent implements OnInit {

  clients = ['john', 'jane']
  clientFound = false

  // constructor(private navController: NavController) { }
  constructor(private clientService: ClientService) {

  }

  openClient(client) {
  }
  ngOnInit() {
    this.clientService.subject.next([
      { name: 'Harold', age: 35 }
    ]
    );

}

}

page2component

import { ClientService } from './../clinet-service.service';
import { Component } from '@angular/core';
@Component({
  selector: 'page-2',
  template: '{{clients}}'
})
export class Page2Component {
  client:any;

  constructor(  private clientService: ClientService) {

  }

  ngOnInit(){
    debugger
    let clients = this.clientService.observable.subscribe(clients => console.log(clients));
  }
}

clientService

import { Injectable, OnInit, OnDestroy } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from "rxjs/Observable";

@Injectable()

export class ClientService {
  subject: Subject<any> = new Subject<any>();
  observable: Observable<any> = this.subject.asObservable();


}

actually I didn't like the way of implementation because i try to make simple thing such push data to service and get it in other components but I can't do that.


Solution

  • You can't do that because you make it unnecessary complicated. Here is how you should do :

    HomeComponent

    ngOnInit() {
        this.clientService.subject.next([{
          {name: 'Harold', age: 35 },
          {name: 'Kumar', age: 40 },
        }]);
    }
    

    page2Component

    ngOnInit(){
      let clients = this.clientService.observable.subscribe(clients => console.log(clients));
    }
    

    service

    export class ClientService {
    
      subject: Subject<any> = new Subject<any>();
      observable: Observable<any> = this.subject.asObservable();
    
      constructor() {}
    }