简体   繁体   中英

How to pass a value from one component to another component Angular 2 (No parent child relationship)

Hi i have two components, component1 and component2 . And i have a value, lets say x , and i want to pass the value to one of my component in my app, both have no parent-child or any relationship each other. How can i get the value x in component2 which is been set or created in component1? I know i can use local storage to set the value and get anywhere. Other than that is there any other way to do this? Sorry am new to Angular. Any idea guys? Thanks in advance. currently what i have done in my component1:

window.localStorage.setItem('myVal', JSON.stringify(x));

and in my component2:

let getmyVal: any = JSON.parse(localStorage.getItem("myVal"));

Since there is no relationship between the components, the easiest approach is to go for a publisher-subscriber model. Any component can publish any message, and any other component can subscribe to the said message, using the Observable.

Here is a sample Alert Service we created in one of our application

 import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { Subject } from 'rxjs/Subject'; @Injectable() export class AlertService { private subject = new Subject<any>(); constructor() { } alert(alertType: string, objData: any) { this.subject.next({ type: alertType, data: objData }); } getMessage(): Observable<any> { return this.subject.asObservable(); } } 

Now, to use it between Component1 and Component2 you can do the following.

Component1:

  1. Import the service, ask it to be injected by Angular and use it. Here is the code for Component 1.

 import { Component} from "@angular/core"; import { AlertService } from "../../../services/common/alert.service"; @Component({ selector: 'c1', templateUrl: 'app/components/controls/Note/ComponentOne.component.html' }) export class ComponentOne implements OnInit { constructor(private _alertService: AlertService) { } AlertMyMessage(): void { this._alertService.alert("SampleAlertType", "ComponentOneAlert"); } } 

Component 2:

Now, component 2 subscribes to the message. Here is the code:

 import { Component, OnInit} from "@angular/core"; import { AlertService } from "../../../services/common/alert.service"; @Component({ selector: 'C2', templateUrl: 'app/components/ComponentTwo.component.html' }) export class ComponentTwo implements OnInit { constructor(private _alertService: AlertService) { } //Subscribing to the alert service on component initialization by providing an handler. ngOnInit(): void { this._alertService.getMessage().subscribe(data => this.alertReceived(data)); } //This method is the event handler. private alertReceived(data: any) { console.log(data.data); } } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM