4

First Component.ts

onRecievingResults(value){
    console.log(value);
    this.faqService.saveData(value);
    console.log(value);
    this.router.navigate(['results'], {relativeTo: this.route});}
}

In this onRecievingResults() function, on click of a button, I am saving the input text to a method saveData() in a service known as faqService.

Service.ts

saveData(value){
    console.log("save data function called " + value + this.sharingData.name);
    this.sharingData.name;
}
getData()
{
    console.log('get Data function called ');
    return this.sharingData.name;
}
getServers(name){
    return this.http.get(Staticdata.apiBaseUrl + "/2.2/search/advanced?key="+ Staticdata.key +"&access_token="+ Staticdata.access_token +"&/2.2/search/advanced?order=desc&sort=activity&accepted=True&closed=True&title=" + name + Staticdata.redirectUrl + "&filter="+ Staticdata.filters)
        .map(
        (response: Response) => {
            const items = response.json();
            return items;
        },
    )
    .catch(
        (error: Response) => {
            return Observable.throw(error);
        }
    );  
  }
}

In this service I have 3 methods getData(), here I get the value from the first component and store it in another method known as saveData(). getServers() method is used to make Http request.

Second component.ts

export class SearchResultsComponent implements OnInit {

 data: any[];   
 item: any[];
 myName:any;

 constructor(private service: FaqService) {
  this.service =  service;
  console.log('back called');
  this.myName = service.getData();  
  console.log(this.myName);
 }

 ngOnInit() {
  this.service.getServers(this.myName)
        .subscribe(
        (data) => {
            this.item= data.items;
            console.log(this.item);
        },
        (error) => console.log(error)
    ); 
    }
  }

Here in this, I call the method getData() to get the value and get the results from the Http request.

The problem here is it takes junk value and gives the results. How to dynamically take text from inputbox and store it in service and pass it to the other component.

Samson Maben
  • 310
  • 2
  • 4
  • 15
  • See if this [answer](https://stackoverflow.com/a/45166374/5556177) helps :) – Nehal Aug 02 '17 at 14:12
  • How do i tell the second component that data has been updated and give results for that. Here it take undefined values and gives the result. @Nehal – Samson Maben Aug 02 '17 at 15:18
  • You will need to use `Observable` and `Subject` then. Here's an [example](https://stackoverflow.com/documentation/angular/10836/sharing-data-among-components/32498/sending-data-asynchronous-from-parent-to-child-using-observable-and-subject#t=201708021524189203765) from the doc and the [plunker](https://plnkr.co/edit/vocFx7eoxtE10AvgiwLG?p=preview) – Nehal Aug 02 '17 at 15:33
  • Could you please demonstrate that for the above posted codes. would be of great help. @Nehal – Samson Maben Aug 03 '17 at 03:35

1 Answers1

5

You can make the second component aware of changes by creating share service using Observable and BehaviorSubject and updating myName variable using the next() method.

service.ts:

  sharingData = { name: " " };

  // Observable string source
  private dataStringSource = new BehaviorSubject<string>();

  // Observable string stream
  dataString$ = this.dataStringSource.asObservable();

  constructor(private http: Http) { }

  public saveData(value){
    console.log("save data function called " + value + this.sharingData.name);
    this.sharingData.name = value;
    this.dataStringSource.next(this.sharingData.name);
  }

first.component.ts:

  constructor(private router: Router, private faqService: FaqService){ }

  ngOnInit(){

  }

  onRecievingResults(value){
    console.log(value);
    this.faqService.saveData(value);
    this.router.navigate(['results']);
  }

second.component.ts:

item: any[];
myName:any;

  constructor(private router: Router, private service: FaqService){

    this.service.dataString$.subscribe(
      data => {
        if(this.myName !== data){
          this.myName = data;
          this.getServersData(this.myName);
        }
      });
  }

This is the plunker demo

Nehal
  • 13,130
  • 4
  • 43
  • 59