0

I am working with Angular 2 and I have 2 different components in the application.

I am trying to transfer data from one component to another, but I am not able to transfer data with input and output parameters.

I am using following code to transfer data.

@Output()
previousurl: EventEmitter<string> = new EventEmitter<string>();

transferdata()
{
    this.previousurl.emit("Hello");
}

Above code i am using to emit the data.

@Input() previousurl: string;

And above code is using to receive data.

Please correct if I am doing wrong.

Thanks.

robbannn
  • 5,001
  • 1
  • 32
  • 47
Prince Chopra
  • 167
  • 11

1 Answers1

0

As mentioned in the comments, you need to use a service something like this:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class PreviousUrlService {

  previousUrl: Observable<string>;

  private previousUrlSubject: Subject<string>=new Subject();
  constructor() {
    this.previousUrl = this.previousUrlSubject.asObservable();
  }

  updatePreviousUrl(prevUrl: string) {
    this.previousUrlSubject.next(prevUrl);
  }

}

And the components need to be injected with the service.

export class ComponentAComponent implements OnInit {

  previousUrl:string;
  constructor(private previousUrlService: PreviousUrlService) {

  }

  ngOnInit() {
    this.previousUrlService.previousUrl.subscribe((data) => {
      this.previousUrl=data;
      console.log('>> previous url', this.previousUrl);
    });
  }

}

And then component B can change the value and it fires in component A subscription function

export class CompBComponent implements OnInit {

  constructor(private previousUrlService: PreviousUrlService) {
  }

  ngOnInit() {

  }

  onUpdateUrl(prevUrl: string){
    this.previousUrlService.updatePreviousUrl('http://google.com');
  }

}

This is the general idea experiment with different types of subjects to suit ur needs.

Sameh Awad
  • 324
  • 2
  • 8
  • Yes, I am also transferring data with service, I was wondering that if it is possible with input and output parameters. – Prince Chopra Mar 28 '18 at 11:55
  • If the two components are not parent and child then using inputs and outputs is not a good idea. A workaround if they are siblings (direct descendents of the same parent), is to use inputs and outputs on both components. Subscribe the parent for both event emitters(outputs) and when the events are fired, it can propagate the change to the inputs of the children. But I really don't recommend this as it is very tightly coupled. – Sameh Awad Mar 28 '18 at 12:09