Ensuring the seamless transfer of data between components is crucial in Angular development. One common way to achieve this is by utilizing observables. Let's take a look at how observables are implemented in a service:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/RX'
@Injectable()
export class SelectedItemService {
stream1$:Observable<any>;
selectedItem:JSON;
stream1$= new Observable(observer=> setTimeout(() => {
observer.next(this.selectedItem);
}, 3000);)
}
In the parent component, data initialization happens within the onSelect() method:
import { Component } from '@angular/core';
import {Http, Headers,Response } from '@angular/http';
import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import {SelectedItemService} from './selecteditem.service'
@Component({
selector: 'newcomponent',
template:`<p>
</p>
<!-- Rest of the parent component template goes here -->
Meanwhile, the child component should receive data from the subscriber. However, if the displayed data appears as undefined and results in a blank screen, we need to troubleshoot accordingly.
import {Component,Input} from '@angular/core';
import {SelectedItemService} from './selecteditem.service
@Component({
selector:'secondcomponent',
template:`<h1> This is second new Component</h1>
<h1>{{UiSelectedItem}}</h1>
`
})
export class SecondComponent{
UiSelectedItem:JSON;
constructor(public mservice:SelectedItemService) {
// Subscribe to the observable for data retrieval
mservice.stream1$.subscribe(value=>this.UiSelectedItem=value);
}
}