I wanted to send data using subject to another component (for a earning purpose). I am not able to fetch back the data. Here is my code:
app.component.ts
import { Component } from '@angular/core';
import { shareService } from './share.service';
@Component({
selector: 'my-app',
template: `
<hello></hello>
<button (click)="passData()">
Start
</button>
`,
styleUrls: [ './app.component.css' ],
providers:[shareService]
})
export class AppComponent {
constructor(private service : shareService){}
passData(){
this.service.send("hello");
}
}
hello.component.ts
import { Component, Input } from '@angular/core';
import { shareService } from './share.service';
import { Subscription } from 'rxjs/Subscription';
@Component({
selector: 'hello',
template: `<h1>Hello!</h1>`,
styles: [`h1 { font-family: Lato; }`],
providers:[shareService]
})
export class HelloComponent {
subscription: Subscription;
constructor(private share : shareService){
this.subscription = share.subj$.subscribe(val=>{
console.log(val);
})
}
}
share.service.ts
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class shareService{
private sub = new Subject();
subj$ = this.sub.asObservable();
send(value: string) {
this.sub.next(value);
}
}
I am not getting the value in console.
Here is the working Demo : DEMO
If you want to pass data from the child component to the parent component use @Output() and EventEmitter. To pass data from the child to the parent, you have to emit it from the child. The parent will be listening for the event will grab the data.
When we build components in an application, we maybe need to share or send data from parent to child or without a direct connection. Angular provides different these ways to communicate components: Using Input() and Output() decorators. Using Viewchild decorator.
By putting:
@Component({
.....
providers: [sharedService]
})
in both components, you are creating two distinct instances of the shared service. Each instance is not 'aware' of the data from each component. Provide it at module level and create a singleton service:
@NgModule({
....
providers: [sharedService]
})
This way, you inject the service as a single instance in the both components, so they can share it as they will share the data.
Or using the Angular's preferred new way :
Beginning with Angular 6.0, the preferred way to create a singleton service is to specify on the service that it should be provided in the application root. This is done by setting providedIn to root on the service's @Injectable decorator:
@Injectable({
providedIn: 'root',
})
Demo
See also
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With