let's implement how to use subject in angular,
first we create 2 component , component1 and component2
this is such as share data among different component,
via Serrvice,
we will create simple input and share texInput to another component
first we create function in component1.ts
in component ts
enteredText: string;
clickFun(){
console.log(this.enteredText)
}
in componenten1.html
<div class="container">
<input type="text" [(ngModel)]="enteredText">
<button (click)="clickFun()">click</button>
</div>
in the top input text in comp1
and text comp2 work from component2
and now create component2
<div class="container">
<p>
comp2 works! {{inputText}}
</p>
</div>
and in component2 ts
inputText : string
and now create service for share data from input component1 into component2
datasubject = new Subject<string>();
shareDataText(data: any) {
this.datasubject.next(data.toString()); //
}
and dont forget for import Subject from rxjs
if we already create service
now we call the service in the app.module
exactly at providers: [NameService]
let call service in component1
constructor(private dataservice: DataService) { }
dont forget to import the service
and now we create call in our clickbutton function
clickFun(){
this.dataservice.shareDataText(this.enteredText)
}
and we call the service in component2
ngOnInit() : void{
this.dataservice.datasubject.subscribe(value => {
this.inputText = value
})
}
and we see when we click input button in component1
data will show in component2
Top comments (0)