I want to send the value from one component to another, they are not related so all solutions are saying that I must use shared service to do that. But these services are using templates (if I’m right). Is there a way to do this sharing without services?
I want to send the BMI value from homepage.component.ts to result.component.ts.
homepage.component.ts:
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-homepage', templateUrl: './homepage.component.html', styleUrls: ['./homepage.component.css'] }) export class HomepageComponent implements OnInit { constructor() { } myHeight!:number; myWeight!:number; bmi!:number; ngOnInit(): void { } onGenerate( height:string,width:string){ this.myHeight = +height; this.myHeight=Math.pow(this.myHeight/100,2); this.myWeight = +width; this.bmi=this.myWeight/this.myHeight console.log(this.bmi); //this is the calculated value to send } }
result.component.ts:
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-result', templateUrl: './result.component.html', styleUrls: ['./result.component.css'] }) export class ResultComponent implements OnInit { constructor() { } //I want to get the bmi here ngOnInit(): void { } }
Advertisement
Answer
If your components are not related then you can create a shared service between them. Then, you need to use dependency injection to communicate between these components. So, there is a great Angular tutorial which describes how to do it.
The service code would look like this:
@Injectable() export class FooService { constructor( ) { } private yourData; setData(data){ this.yourData = data; } getData(){ let temp = this.yourData; this.clearData(); return temp; } }
and sender component:
import { Router } from '@angular/router'; import { FooService} from './services/foo.service'; export class SenderComponent implements OnInit { constructor( private fooService: FooService, private router:Router) {} somefunction(data){ this.fooService.setData(data); this.router.navigateByUrl('/reciever');//as per router } }
and subscriber:
import { Router } from '@angular/router'; import { TransfereService } from './services/transfer.service'; export class RecieverComponent implements OnInit { data; constructor( private fooService: FooService){ } ngOnInit() { data = this.transfereService.getData(); console.log(`data: `, data) } }