2

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.

7
  • what is the error Commented Sep 7, 2017 at 9:04
  • I don't see nothing in page2 Commented Sep 7, 2017 at 9:07
  • You are not getting anything in console? Commented Sep 7, 2017 at 9:09
  • yes i don't get anything Commented Sep 7, 2017 at 9:12
  • What happens when you remove the debugger line from Page2Component in ngOnInit method? Commented Sep 7, 2017 at 9:25

3 Answers 3

4

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() {}
}
Sign up to request clarification or add additional context in comments.

17 Comments

I tried to do that in parent and child project and the child load before the parent and it not works so I decided to do that with observable
Well if you use an API after that (I guess that your service is mocked), you won't have this problem, since you won't set your clients, but just get them. To check that, you can set the clients in the service directly where you declare the clients variable.
it works but it's not what I want to do. I want from parent component to get data and then to save in service and share with all childs.. all childs use get function to get data in their components
Well for that, unmock your service and edit your post. Then, we'll work on that. Because if you don't, we'll use concepts that aren't related to a real API service.
what do you mean @trichetriche?
|
1

Your HomeComponent decorator is broken. You need to use templateUrl instead of template when you are using external template file.

Wrong

@Component({
  selector: 'page-home',
  template: 'pages/home/home.html',
})

Correct

@Component({
  selector: 'page-home',
  templateUrl: 'pages/home/home.html',
})

https://angular.io/api/core/Component

1 Comment

i did it in purpose just write a text with the url
1

You can pass the data between any of the componenrs using rxjs subject. Create new rxjs subject in your service like this

import { Subject } from 'rxjs/Subject';
@Injectable()
export class MyService {

    myNewSubject = new Subject<any>();

    informDataChanges(passyourobject){
      this.myNewSubject.next(passyourobject);
  }

}

When change happens in your component or you want to pass data to another component simply call this service function from your component and pass data as parameter to this function. You can do that with something like this

    import { Component, OnInit } from '@angular/core';

    @Component({
      selector: 'app-some',
      templateUrl: './some.component.html',
      styleUrls: ['./some.component.css']
    })
    export class SomeComponent implements OnInit {

      constructor( private myService: MyService) { }

      someFunction(){
        this.myService.informLogout('somedata');//Passing data to service here
      }

  ngOnInit() {

  }

}

Now all you need to do is subscribe to that data in another component. IMPORTANT subject keeps on watches any changes to it, and data will be continuous stream and it will be automatically subscribed. So it is best to subscribe to the subject in the constructor, and changes will be immediately reflected in that component.

You do it with some thing like this

import { Component, OnInit } from '@angular/core';

        @Component({
          selector: 'app-another',
          templateUrl: './another.component.html',
          styleUrls: ['./another.component.css']
        })
        export class AnotherComponent implements OnInit {

          constructor( private myService: MyService) {
            this.myService.myNewSubject.subscribe(data=>{
             console.log(data);
       }) 
}

This way you can pass data between any number of components and any number of components can use the same subject.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.